× The Medium App
An app designed for readers.
OPEN IN APP
Handling multiple
checkboxes in [Link]
Jakub Włodarczyk Follow
Jun 16, 2018 · 2 min read
Need a freelancer (or consultations / help) for a project or
want to build a showcase project? Hire me. Expertise: JS,
[Link], Redux, [Link] and leave a message or
contact@[Link].
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 [Link]. Let’s create some config file for
the checkboxes:
1 const checkboxes = [
2 {
3 name: 'check-box-1',
4 key: 'checkBox1',
5 label: 'Check Box 1',
6 },
7 {
8 name: 'check-box-2',
9 key: 'checkBox2',
10 label: 'Check Box 2',
11 },
12 {
13 name: 'check-box-3',
14 key: 'checkBox3',
15 label: 'Check Box 3',
16 },
17 {
18 name: 'check-box-4',
19 key: 'checkBox4',
We need a reusable Checkbox component:
1 import React from 'react';
2 import PropTypes from 'prop-types';
3
4 const Checkbox = ({ type = 'checkbox', name, checked = false, onChange
5 <input type={type} name={name} checked={checked} onChange={onChange
6 );
7
8 [Link] = {
9 type: [Link],
10 name: [Link],
11 checked: [Link],
12 onChange: [Link],
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:
1 import React from 'react';
2 import PropTypes from 'prop-types';
3 import checkboxes from './checkboxes';
4 import Checkbox from './Checkbox';
5
6 class CheckboxContainer extends [Link] {
7 constructor(props) {
8 super(props);
9
10 [Link] = {
11 checkedItems: new Map(),
12 }
13
14 [Link] = [Link](this);
15 }
16
17 handleChange(e) {
18 const item = [Link];
19 const isChecked = [Link];
20 [Link](prevState => ({ checkedItems: [Link]
21 }
22
23 render() {
24 return (
25 <[Link]>
26 {
27 [Link](item => (
28 <label key={[Link]}>
29 {[Link]}
30 <Checkbox name={[Link]} checked={[Link]
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 [Link] (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.
JavaScript React ES6 Web Development Reactjs
About Help Legal