#AD Top Online Web Development & Programming Courses | Udemy

How to create a checkbox component in React

Last modified March 23rd 2022 | #react | GitHub Source Code [GitHub]

A checkbox is a common form element that allows users to mark an input as true or false. Most commonly used for things like agreeing to terms or selecting preferences. In this tutorial we’ll be creating a simple checkbox component in React.

Let’s get started by creating the Checkbox.js component file:

const Checkbox = ({ id, label, value, onChange }) => { return ( <div> <input id={id} type="checkbox" checked={value} onChange={onChange} /> <label htmlFor={id}>{label}</label> </div> ); }; export default Checkbox;
Code language: JavaScript (javascript)

This is just a standard HTML input checkbox and label. We’ll provide the id, label, value, and onChange parameters when the component is loaded which will allow for multiple checkboxes to be used from this component.

Now we can load the component into our App.js as follows:

import { useState } from "react"; import Checkbox from "./Checkbox"; function App() { const [checked, setChecked] = useState(false); const onChange = () => { setChecked(!checked); }; return ( <div className="App"> <Checkbox id="checkbox" label="I agree to the terms and conditions." value={checked} onChange={onChange} /> </div> ); } export default App;
Code language: JavaScript (javascript)

Let’s quickly go over what’s happening here:

  • checked state is stored using the useState hook defaulted to false.
  • onChange function toggles the checked state between true & false.
  • <Checkbox/> component with the parameters that get passed to the input field.

That’s all for this tutorial. You now should have a fully functioning re-usable React checkbox component. There is some more complexity when you want to include multiple checkboxes which we’ll save for it’s own dedicated tutorial.

Related Posts

#AD Shop Web Developer T-Shirts