No Time Dad

A blog about web development written by a busy dad

Quick React Checkbox Example

This might be one of my most used patterns in React. Click an element to update a state value, and use that state value somewhere else. This is a react checkbox example, but the pattern applies to any type of react element. In the example below, clicking on the checkbox updates the component state, causing the compont to re-render and display new text to the right.

Not checked
import React, { useState } from "react"

export const Checkbox = () => {
  const [checked, setChecked] = useState(false)
  return (
    <>
      <input
        type="checkbox"
        checked={checked}
        id="checkbox"
        onChange={() => setChecked(!checked)}
      />
      <label for="checkbox">Check me!</label>
      <div>{checked ? "Checked" : "Not checked"}</div>
    </>
  )
}
"react": "^17.0.2"

This example uses React’s useState hook to track and update the state of the input checkbox. The input checkbox has an attribute called checked that determines if the it should be checked by default when the page loads. In this example, I don’t want the it to be checked when the page loads so I set the state variable to false and pass the variable to the input attribute.

In doing this I have created a React controlled component. Which means that the input is no longer tracking it’s own state and is instead relying on the state I’ve initialized in the component itself.

Since the input no longer track it’s own state, I’m responsible for updating the state so it knows when it has been checked. This is done with an onChange handler that sets the value of checked defined in the useState hook to the opposite of its current value. The value should switch between true and false. The ! is the logical NOT operator, which shortens a verbose if else block to set the value of checked.

onChange={() => setChecked(!checked)}

Now that I have a working controlled input component, I want to use the state value somewhere else in the component. There are lots of different things I can do with this value, including updating parts of the page, or sending selectewd data to the database. The latter is more common with checkboxes when used in a table with selectable items.

For this simple example I opted to just show dynamic text. I did this with a ternary operator that switches between the text “Checked” and “Not checked” based on the value of the checked state variable. As mentioned above, each time the state value changes the component will re-render and the value of checked will be evaluated again by the input element and the ternary operator below.

<div>{checked ? "Checked" : "Not checked"}</div>