AppDividend
Latest Code Tutorials

How To Save Multiple Checkboxes Values in React js

739

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see How To Save Multiple Checkboxes Values in React js. If you are building a web application, then there are lots of form controls we need to create an interactive user form. The checkbox is one of the most used form control in a web application. We will take three checkboxes and user can check multiple boxes and save its values inside MongoDB database. As we know, form control values are always controlled by 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.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

How To Save Multiple Checkboxes Values in React

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

#1: Install React.js

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

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

// App.js

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

#2: Create Form inside an App.js.

For this example, I am merely taking the checkboxes and not other input types. 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 check 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, then we send it to the server and save the data in the MongoDB database.

#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 into 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 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.

#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;

#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 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.

Related Posts
1 of 20
// 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 are 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, then 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

Finally, our How To Save Multiple Checkboxes Values in React js Tutorial Example is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

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