Posts Handle multiple checkboxes in react
Post
Cancel

Handle multiple checkboxes in react

This example shows one way to handle multiple checkboxes in react and populates an array with the ID of the checked checkboxes.

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import React from "react";

const checkboxes = [
  { id: 1, text: "Checkbox 1" },
  { id: 2, text: "Checkbox 1" },
  { id: 3, text: "Checkbox 1" }
];

class SearchResults extends React.Component {
  state = {
    selectedCheckboxes: []
  };

  onChange = id => {
    const selectedCheckboxes = this.state.selectedCheckboxes;

    // Find index
    const findIdx = selectedCheckboxes.indexOf(id);

    // Index > -1 means that the item exists and that the checkbox is checked
    // and in that case we want to remove it from the array and uncheck it
    if (findIdx > -1) {
      selectedCheckboxes.splice(findIdx, 1);
    } else {
      selectedCheckboxes.push(id);
    }

    this.setState({
      selectedCheckboxes: selectedCheckboxes
    });
  };
  render() {
    const { selectedCheckboxes } = this.state;
    return (
      <div className="App">
        {checkboxes.map(checkbox => (
          <label key={checkbox.id}>
            {checkbox.text}
            <input
              type="checkbox"
              onChange={() => this.onChange(checkbox.id)}
              selected={selectedCheckboxes.includes(checkbox.id)}
            />
          </label>
        ))}
        <p>Selected checkboxes: {JSON.stringify(selectedCheckboxes)}</p>
      </div>
    );
  }
}

export default SearchResults;

Demo

This post is licensed under CC BY 4.0 by the author.