Handling multiple checkboxes in React.js

Need a freelancer (or consultations / help) for a project or want to build a showcase project? Hire me. Expertise: JS, React.js, Redux, Node.js.Click and leave a message or contact@developeryourself.com.
Want to get a Web Developer job having no experience? I provide one-to-one on-line training. Click here.

I’ll show you an example implementation of how you can handle multiple checkboxes in React.js. Let’s create some config file for the checkboxes:

We need a reusable Checkbox component:

Parameter destructuring is used in the function signature along with some default values. So the initial state of all of the checkboxes will be unchecked.

Let’s use the Checkbox component by wrapping it in a container:

In state we have checkedItems which is a Map. This construct is used for flexibility and convenience of just setting and getting values. In the render method we use React.Fragment (find out more), loop through our checkboxes config array and return the Checkbox component for each item. In the handleChange method we set a Map key (represented by checkbox name) with a boolean value for a current item. This is later used in the render method in the checked prop to determine if the checkbox should be checked / unchecked.

State keeps the information which checkboxes were checked / unchecked so we can use this information and e.g. dispatch some action with the values or call some function.

Check for more inspiration here.