Checkbox

This component allows you to create multiple checkboxes. What you need to do is create an object with boolean values, and then extract the useCheckbox hook (as shown below).

You should pass this object as the value for the initialCheckbox property. This hook returns one variable (checkboxState) and two functions (handleCheckboxChange and resetCheckbox).

The state variable checkboxState contains the state of all the checks and each value is accessed as checkboxState.checkA, etc or from the hook you can also extract the form properties. The handleCheckboxChange function sets the status of each check. resetCheckbox resets it to its initial state.

The 'name' prop is required to handle all the states correctly and it must be called exactly the same as the properties of the object

If you only need a single checkbox, you'll encounter an error because this hook is designed to receive objects. If you want to control just one checkbox, you'll find how to use useState with that component later on.

import { useCheckbox } from "dialui-components/dist/hooks";
import { Checkbox } from "dialui-components";

const initialCheckbox = {
  checkA: false,
  checkB: true,
};

export const MyComponent = () => {
  const { checkboxState, handleCheckboxChange } = useCheckbox({ initialCheckbox });
  // Alternative:
  // const { checkA, checkB, handleCheckboxChange } = useCheckbox({ initialCheckbox });

  return (
    <>
      <Checkbox
        checkboxFormState={checkboxState}
        handleCheck={handleCheckboxChange}
        name="checkA"
      />
      <Checkbox
        checkboxFormState={checkboxState}
        handleCheck={handleCheckboxChange}
        name="checkB"
      />
    </>
  );
};

Default Props:

  • name= required;
  • checkboxFormState= required;
  • handleCheck= required;

Props:

  • name: string;
  • checkboxFormState: Record<string, boolean> | boolean;
  • handleCheck: (event: ChangeEvent<HTMLInputElement>) => void;

A single checkbox:

import { useState } from "react";
import { Checkbox } from "dialui-components";

export const MyComponent = () => {
  const [checkboxState, handleCheckboxChange] = useState(false);

  return (
    <Checkbox
      checkboxFormState={checkboxState}
      handleCheck={() => handleCheckboxChange(!checkboxState)}
      name="check"
    />
  );
};