Checkboxes are one of the most common and useful types of inputs in React.

React Checkbox onChange

When set on a checkbox, onChange event handler runs every time there’s a change – the checkbox is ticked or unticked.

Keep in mind that change event will happen not only for select, but also when user de-selects the checkbox.

onChange to check whether checkbox is selected

Let’s say you have a checkbox and want to keep track of its status – is it selected or not selected?

You might want to conditionally change elements’ appearance depending on whether or not the checkbox is selected.

All event handlers accept one argument – SyntheticEvent. This object contains essential information about the event that happened. In this case, information about the change of checkbox.

In the function definition, React developers name this argument event.

When the event happens and your function is provided with instance of SyntheticEvent, you event.target.checked will be true if the checkbox is selected, false if not.

Let’s look at an example:

function App() {
  const [checked, setChecked] = useState(false);
  return (
    <div className="App">
      Checked or not
      <input
        type="checkbox"
        onChange={(event) => setChecked(event.target.checked)}
      />
      <p>{checked ? "Yes" : "Not checked"}</p>
    </div>
  );
}

Whenever a checkbox is selected (or de-selected), onChange event handler accesses its current status (selected or not) on event.target.checked and stores it in the state.

Inside the JSX, we embed a ternary operator that uses ternary operator to render appropriate text depending on whether the checkbox is selected or not.

onChange to get checkbox value

Sometimes a checkbox has a specific value.

Let’s say you want users to select checkboxes to specify their preferences.

<input
        type="checkbox"
        value="strawberry"
        onChange={(event) => console.log(event.target.value)}
      />

In this case, we use event.target.value to access value of the checkbox.

Note that event.target.value shows the value of the checkbox, not whether or not it is selected. That information is stored as a Boolean on event.target.checked.

onChange to toggle checkbox

Finally, some React developers also set onChange handler to use checkbox as a toggle.

For example, let’s say you have a darkMode state variable. If it’s true, you want to turn on the dark mode – apply styles so your app has darkbackground on white text, and if it’s false, vice versa.

Every time there’s a change to a checkbox, you might want to change current value of darkMode. Simply flip the switch, regardless of input’s value.

<input
        onChange={() => setDarkMode(!darkMode)}
 />

In this case, the current value of checkbox does not matter. Whenever checkbox is selected / deselected, event handler will flip current Boolean value of darkMode variable.