How to Handle Multiple Checkboxes Value in React

React dynamic checkbox component tutorial; This handy guide explains how to create reusable multiple checkbox component in react, similarly how to get multiple checkboxes values in React and how to store checkbox values into the database on form submit in react application.

Ideally, the checkbox is a functional graphical user interface element. It allows users to select single or multiple options from the given list of options, also known as choice.

Visually, checkboxes are square-boxes, with checked and unchecked state, in general in regular HTML page, it is created using the <input type="checkbox"> HTML element. The checkbox element supports all the major versions such as chrome, internet explores, firefox, safari in the same way in opera.

In this tutorial, we will also use the axios package to make an HTTP request to learn to create a checkbox in react, get multiple checkbox values, and store the checkbox values in the server. To store the value, we will use the json-server package; additionally, we will learn to set up the test server and use the fake rest api in react.

React Multiple Checkboxes Example

  • Step 1: Install React Project
  • Step 2: Add Bootstrap Pacakage
  • Step 3: Set Up JSON Server
  • Step 4: Install Axios Pacakage
  • Step 5: Update App.js File
  • Step 6: Run Development Server

Install React Project

If you have installed a react app, skip this step; otherwise, run the recommended command, and generate a fresh new react application.

npx create-react-app react-demo-app

Get inside the project folder.

cd react-demo-app

Add Bootstrap Pacakage

We are using the bootstrap library to style the HTML component in React; however, if you want, you may avoid using the Boostrap; this is an optional step.

npm install bootstrap

To build the UI component with ease, make sure to import the Bootstrap CSS in the main src/App.js file.

import React, { Component } from 'react';

import '../src/App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() {
    return (
      <div className="multiCb container">
        
      </div>
    );
  }
}

export default App;

Set Up JSON Server

Creating REST API is not a difficult but time taking process to cut down that time-related issue. We may certainly rely on the json-server package.

It lets you set up a fully functional backend server, and the great thing is you can make handy fake REST API within exorbitantly less time.

npm i json-server

After that, create a db.json file at the root of your react project; after that, pour the following data nto the db.json file.

{
  "posts": [
     
  ]
}

This file will be updated when you store the checkbox values using the following REST API.

http://localhost:3000/posts

Install Axios Pacakage

Now, REST API is ready, and we need a mechanism that helps us make the request to the server; ideally, Axios is the library that can help us communicate to the server.

npm install axios

Update App.js File

We have placed everything under the hood; now its time to conjugate every code inside the src/App.js file.

import React, { Component } from 'react';

import '../src/App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios';

class App extends Component {

  state = {
    Inception: false,
    Avatar: false,
    Parasite: false,
  };

  onChange1 = () => {
    this.setState(res => ({
      Inception: !res.Inception,
    }));
  }

  onChange2 = () => {
    this.setState(res => ({
      Avatar: !res.isOrange,
    }));
  }

  onChange3 = () => {
    this.setState(res => ({
      Parasite: !res.isBanana,
    }));
  }


  // Submit checkbox
  onFormSubmit = (event) => {
    event.preventDefault();
    let checkboxCollection = [];
    
    for (var key in this.state) {
      if (this.state[key] === true) {
        checkboxCollection.push(key);
      }
    }

    let ifChecked = {
      checkbox: checkboxCollection.toString()
    };
    
    if(ifChecked.checkbox == "") {
       alert('Select atleast one value');
       return false;
    } else {
      axios.post('http://localhost:3000/posts', ifChecked)
      .then((response) => {
         console.log(response.data)
      }).catch((err) => {
         console.log(err)
      });
    }


  }

  render() {
    return (
      <div className="multiCb container">
        <form onSubmit={this.onFormSubmit}>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.Inception}
                onChange={this.onChange1}
                className="form-check-input"/>
              Inception
            </label>
          </div>

          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.Avatar}
                onChange={this.onChange2}
                className="form-check-input"/>
              Avatar
            </label>
          </div>

          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.Parasite}
                onChange={this.onChange3}
                className="form-check-input"/>
              Parasite
            </label>
          </div>

          <div className="form-group">
            <button type="submit" className="btn btn-primary">Submit</button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

Run Development Server

The development part is done, we now need to start the react js application, make sure to use the following command:

npm start

When the values, checked and stored then, you can visit your db.json file and see the checkboxes’ stored values.

multiple checkboxes in react

Conclusion

So, this was it; eventually, the react checkbox tutorial is completed; In this detailed guide, we not just shared how to implement multiple checkboxes in react, but we also described how to get checkboxes values and store in the server using the fake REST API. We hope this guide will help your react development voyage and relentlessly enhance your react front-end development skills.