How to Save Multiple Checkboxes Values in React

If you are building a web application, there are many form controls we need to create an interactive user form. The checkbox is one of the most used form control in a web application.

How to Save Multiple Checkboxes Values in React

To save multiple checkbox values in React, convert the checkbox values to a string and filter the state, and if any of the checkbox values are true, we add to an array and then change that array into the string and send that data to the server.

In this example, we will take three checkboxes, and users can check multiple boxes and save their values inside the MongoDB database. As we know, form control values are always controlled by the React.js state. So when the user submits the form, we need only to send the values of checkboxes whose values are valid or whose checkbox values are checked.

We save the values as a String in a MongoDB database. We use Node.js as a platform. There are many ways you can save multiple checkbox values in React js inside the MongoDB database.

Step 1: Install React.js

First of all, let us install React.js using the following command.

npx create-react-app checkbox

Now, go inside the folder, and we need to install the bootstrap and axios libraries.

yarn add bootstrap axios

# or

npm install bootstrap axios --save

The next step is to import the bootstrap css file inside the src >> App.js file.

// App.js

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

Step 2: Create Form inside an App.js.

I am merely taking the checkboxes and not other input types for this example. So I am making three textboxes. So, first, we need to define the three initial state values.

// App.js

import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {

  state = {
    isMJ: false,
    isJB: false,
    isDrake: false
  };

  toggleChangeMJ = () => {
    this.setState(prevState => ({
      isMJ: !prevState.isMJ,
    }));
  }

  toggleChangeJB = () => {
    this.setState(prevState => ({
      isJB: !prevState.isJB,
    }));
  }

  toggleChangeDrake = () => {
    this.setState(prevState => ({
      isDrake: !prevState.isDrake,
    }));
  }

  onSubmit = (e) => {
    e.preventDefault();
    console.log(this.state);
  }

  render() {
    return (
      <div className="container">
        <h2>Save the multiple checkbox values in React js</h2>
        <hr />
        <form onSubmit = {this.onSubmit}>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isMJ}
                onChange={this.toggleChangeMJ}
                className="form-check-input"
              />
              MJ
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isJB}
                onChange={this.toggleChangeJB}
                className="form-check-input"
              />
              JB
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isDrake}
                onChange={this.toggleChangeDrake}
                className="form-check-input"
              />
              Drake
            </label>
          </div>
          <div className="form-group">
            <button className="btn btn-primary">
              Submit
            </button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

We have defined the three initial states. Each state is for one checkbox. 

We also need to handle the change event. So when the user either checks the checkbox or uncheck the checkbox, the state will be changed. So when the user submits the form, we get all the three-state, and if any of the checkboxes are checked, we send it to the server and save the data in the MongoDB database.

Step 3: Convert checked values into String.

We will save the string into the database. The String is comma-separated values. So, we filter the state, and if any of the checkbox value is right or true, we add to an array and then finally change that array into the string and send that data to the Node.js server.

So, write the following code inside the onSubmit() function.

// App.js

onSubmit = (e) => {
    e.preventDefault();
    let arr = [];
    for (var key in this.state) {
      if(this.state[key] === true) {
        arr.push(key);
      }
    }
    let data = {
      check: arr.toString() 
    };
}

So, here as I have explained, the first loop through the states, and if the value is true, we push into the new array and finally cast that array into the String.

Step 4: Use Axios to send a POST request.

Import the axios module and send the POST request to the node server. So our final App.js file looks like below.

// App.js

import React, { Component } from 'react';
import axios from 'axios';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {

  state = {
    isMJ: false,
    isJB: false,
    isDrake: false
  };

  toggleChangeMJ = () => {
    this.setState(prevState => ({
      isMJ: !prevState.isMJ,
    }));
  }

  toggleChangeJB = () => {
    this.setState(prevState => ({
      isJB: !prevState.isJB,
    }));
  }

  toggleChangeDrake = () => {
    this.setState(prevState => ({
      isDrake: !prevState.isDrake,
    }));
  }

  onSubmit = (e) => {
    e.preventDefault();
    let arr = [];
    for (var key in this.state) {
      if(this.state[key] === true) {
        arr.push(key);
      }
    }
    let data = {
      check: arr.toString() 
    };
    axios.post('http://localhost:4000/checks/add', data)
          .then(res => console.log(res.data));
  }

  render() {
    return (
      <div className="container">
        <h2>Save the multiple checkbox values in React js</h2>
        <hr />
        <form onSubmit = {this.onSubmit}>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isMJ}
                onChange={this.toggleChangeMJ}
                className="form-check-input"
              />
              MJ
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isJB}
                onChange={this.toggleChangeJB}
                className="form-check-input"
              />
              JB
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isDrake}
                onChange={this.toggleChangeDrake}
                className="form-check-input"
              />
              Drake
            </label>
          </div>
          <div className="form-group">
            <button className="btn btn-primary">
              Submit
            </button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

Step 5: Create a Node.js backend.

First, start the mongodb server using the following command.

mongodb

Now, create one folder inside the root of the checkbox – our react project folder called backend and go inside that folder and initialize the package.json file.

npm init -y

Now, install the following dependencies for the node project.

yarn add express body-parser mongoose cors

# or

npm install express body-parser mongoose cors --save

Now, create a database connection using the following command.

// DB.js

module.exports = {
  DB: 'mongodb://localhost:27017/checks'
};

Now, create the routes and models folders inside the backend folder.

Inside the models folder, create one file CheckModel.js add the following code.

// CheckModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let CheckModel = new Schema({
  check: {
    type: String
  },
},{
    collection: 'checks'
});

module.exports = mongoose.model('CheckModel', CheckModel);

Also, you need to create the check.route.js file. Add the following code inside that file.

// CheckRoute.js

const checkRoute = require('express').Router(),
  CheckModel = require('../models/CheckModel');

  checkRoute.route('/add').post(function (req, res) {
    let checkmodel = new CheckModel(req.body);
    checkmodel.save()
      .then(Checkvalue => {
        res.status(200).json({'Checkvalue': 'Checkbox values have added successfully'});
      })
      .catch(err => {
        res.status(400).send("unable to save to database");
      });
  });

module.exports = checkRoute;

Finally, our server.js file looks like this.

// server.js

const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose')
  config = require('./DB'),
  checkRoute = require('./routes/check.route');

  mongoose.Promise = global.Promise;
  mongoose.connect(config.DB, { useNewUrlParser: true }).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
  );

  const PORT = process.env.PORT || 4000;

  app.use(bodyParser.json());
  app.use(cors());

  app.use('/checks', checkRoute);

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

Open the terminal inside the backend folder and hit the following command.

node server

So, now you have three servers running.

  1. React Development Server
  2. Node server
  3. MongoDB server

Go to the browser and navigate to this URL: http://localhost:3000/

You can see this page.

How To Save Multiple Checkboxes Values in React js

 

Now, check the multiple boxes and submit the form. If everything goes correct, you can see the response on your console.

Save multiple checkbox values in React

I have inserted multiple documents, and you can see that inside the following image in the MongoDB database.

Multiple checkbox in React

That’s it for this tutorial. Thanks for taking it.

1 thought on “How to Save Multiple Checkboxes Values in React”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.