How to work with multiple checkbox in React

How to work with multiple checkbox in React Js to change styling

Posted by Ervin Adams on November 6, 2021

In this short lesson you will be shown how to select multiple checkboxes in a list in order to change styling of the list items. In this case we are only going to change the colour of the items.

I am sure they are many different ways to handle the selection of multiple checkboxes within React in order to do something dynamic. However, if you want a quick simple way that works, this might work for you.

Step 1. Create your component

In this case, a class component will be used

export default class MultiSelectCheckbox extends Component {

    render() {
        return (
              <div></div>
        )
    }
}

Step 2. Declare an array within component

This array of objects is a list of grocery items.

    /*list of grocery items in array*/
    listItems = [
        {name:'peas',amount:3},
        {name:'beans', amount:8},
        {name:'bananas', amount:10},
        {name:'oranges', amount:15},
        {name:'peach', amount:5}
    ];

Step 3. Create the list using array map method within render method

In this step a bit of styling is used from Bootstrap and MDBreact to create the list.

The array map method is used to loop through the items and display them in the list. Each item has a unique index which is used to create unique ids.

The unique ids are passed to the handleCheckBox method as params.

Whenever the checkbox in the list is checked the onChange handler calls  handleCheckBox

In the next step we will go through what the handleCheckBox method does.

           <div>
                <MDBCard>
                    <MDBCardHeader>
                        <h4>Grocery List</h4>
                    </MDBCardHeader>
                    <MDBCardBody>
                        <ul className="list-unstyled">
                            {
                                this.listItems.map((value,i)=>{
                                    return (
                                        <li key={i} className="mb-4">
                                            <div id={'wrapper-'+i} className="row">
                                                <label className="col-9 trt-txt">
                                                    <input type="checkbox" id={'input-'+i} className="form-check-input me-1" onChange={this.handleCheckBox.bind(this, 'wrapper-'+i, 'input-'+i, 'count-'+i)} name="hobbies"/>
                                                    <b>{value.name}</b>
                                                </label>
                                                <div className="col-3 text-end"><span id={'count-'+i} className="badge rounded-pill text-dark">{value.amount}</span></div>
                                            </div>
                                        </li>
                                    )
                                })
                            }
                        </ul>
                    </MDBCardBody>
                </MDBCard>
            </div>

Step 4. Create handleCheckBox method

The logic within the handleCheckBox method determines if the list should be higlighted or not.

Within the handleCheckBox method, the javascript get getElementById method can determine if the class used for highlighting the items is added to the HTML elements in the list or not.

If the classes are not added on checkbox checked, then add. Else remove if checkbox is unchecked.   

You can click the checkbox or text within the list to check or uncheck the checkbox.

    handleCheckBox(wrapper, input, count){
        if(!document.getElementById(wrapper).classList.contains("change-txt")) {
            document.getElementById(wrapper).classList.add("change-txt");
            document.getElementById(count).classList.add("change-txt");
            document.getElementById(count).classList.remove("text-dark");
        }else{
            document.getElementById(wrapper).classList.remove("change-txt");
            document.getElementById(count).classList.remove("change-txt");
            document.getElementById(count).classList.remove("change-txt");
            document.getElementById(count).classList.add("text-dark");
        }
    }

Step 5. Add css styling 

Add this block of code in an existing css file. I put it in App.css just for demonstration purposes.

.change-txt{
    color: #054dba;
}

At the end of it your MultiSelectCheckbox component should look like below:

import React, { Component } from 'react';
import {MDBCard, MDBCardBody, MDBCardHeader} from "mdbreact";

export default class MultiSelectCheckbox extends Component {

    /*list of grocery items in array*/
    listItems = [
        {name:'peas',amount:3},
        {name:'beans', amount:8},
        {name:'bananas', amount:10},
        {name:'oranges', amount:15},
        {name:'peach', amount:5}
    ];

    handleCheckBox(wrapper, input, count){
        if(!document.getElementById(wrapper).classList.contains("change-txt")) {
            document.getElementById(wrapper).classList.add("change-txt");
            document.getElementById(count).classList.add("change-txt");
            document.getElementById(count).classList.remove("text-dark");
        }else{
            document.getElementById(wrapper).classList.remove("change-txt");
            document.getElementById(count).classList.remove("change-txt");
            document.getElementById(count).classList.remove("change-txt");
            document.getElementById(count).classList.add("text-dark");
        }
    }

    render() {
        return (
            <div>
                <MDBCard>
                    <MDBCardHeader>
                        <h4>Grocery List</h4>
                    </MDBCardHeader>
                    <MDBCardBody>
                        <ul className="list-unstyled">
                            {
                                this.listItems.map((value,i)=>{
                                    return (
                                        <li key={i} className="mb-4">
                                            <div id={'wrapper-'+i} className="row">
                                                <label className="col-9 trt-txt">
                                                    <input type="checkbox" id={'input-'+i} className="form-check-input me-1" onChange={this.handleCheckBox.bind(this, 'wrapper-'+i, 'input-'+i, 'count-'+i)} name="hobbies"/>
                                                    <b>{value.name}</b>
                                                </label>
                                                <div className="col-3 text-end"><span id={'count-'+i} className="badge rounded-pill text-dark">{value.amount}</span></div>
                                            </div>
                                        </li>
                                    )
                                })
                            }
                        </ul>
                    </MDBCardBody>
                </MDBCard>
            </div>
        )
    }
}

Here is how it looks once you run the app:

Download project here

Please run npm install then npm start if you plan to download the project above.