Hello Devs, 

In this tutorial, we will learn React Multiple Checkboxes Example

In this section, we will take one categories array with "PHP", "Laravel" etc. and simply using map loop display dynamic multiple checkbox. When user will select any checkbox then we will store that info to "checkedItems" variable.

Follow this step by step guide below. 


Example Code:

import React, { Component } from 'react';
import { render } from 'react-dom';
       
class App extends Component {
  constructor() {
    super();
    this.state = {
      categories: [
        {id: 1, value: "PHP"},
        {id: 2, value: "Laravel"},
        {id: 3, value: "Angular"},
        {id: 4, value: "React"}
      ],
      checkedItems: new Map()
    };
  
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
     
  handleChange(event) {
        var isChecked = event.target.checked;
        var item = event.target.value;
         
        this.setState(prevState => ({ checkedItems: prevState.checkedItems.set(item, isChecked) }));
  }
     
  handleSubmit(event) {
    console.log(this.state);
    event.preventDefault();
  }
     
  render() {
    return (
      <div>
        <h1>React Multiple Checkbox Example - rathorji.in</h1>
  
        <form onSubmit={this.handleSubmit}>
           
          {
            this.state.categories.map(item => (
              <li>
                <label>
                  <input
                    type="checkbox"
                    value={item.id}
                    onChange={this.handleChange}
                  /> {item.value}
                </label>
              </li>
            ))
          }
           
          <br/>
          <input type="submit" value="Submit" />
        </form>
      </div>
    );
  }
}
   
render(<App />, document.getElementById('root'));


Output: 

checkedItems: Array[3]

0: Array[2]

0: "1"

1: true

1: Array[2]

0: "3"

1: true

2: Array[2]

0: "4"

1: true


May this example help you.