How to create a React Checkbox - Robin Wieruch

How to create a React Checkbox - Robin Wieruch

A short React tutorial by example for beginners about using a checkbox in React. First of all, a checkbox is just an HTML input field with the type of checkbox which can be rendered in React’s JSX:

What may be missing is an associated label to signal the user what value is changed with this checkbox:

In your browser, this checkbox can already change its checked state by showing either a check mark or nothing. However, this is just the checkbox’s internal HTML state which isn’t controlled by React yet. Let’s change this by transforming this checkbox from being uncontrolled to controlled :

By using React’s useState Hook and an event handler , we can keep track of the checkbox’s value via React’s state . Next we may want to create a Checkbox component which can be used more than once throughout a React project. Therefore, we will extract it as a new function component and pass the necessary props to it:

Our Checkbox component is a reusable component now. For example, if you would give your input element some CSS style in React , every Checkbox component which is used in your React project would use the same style.

If you would want to create a checkbox group now, you could just use multiple Checkbox components side by side and maybe style them with some border and some alignment, so that a user perceives them as a group of checkboxes:

That’s is it for creating a Checkbox component in React. If you are a beginner in React, I hope this tutorial helped you to understand some concepts and patterns!

Recommended articles