Search

How To Save Multiple Checkboxes Values in React js

post-title

In this tutorial, we will optically discern How To Preserve Multiple Checkboxes Values in React js. If you are building a web application, then there are lots of form controls we require to engender an interactive utilizer form. The checkbox is one of the most used form control in a web application. We will take three checkboxes and utilizer can check multiple boxes and preserve its values inside MongoDB database. As we ken, form control values are always controlled by React.js state. So when the utilizer submits the form, we require only to send the values of checkboxes whose values are valid or whose checkbox values are checked. We preserve the values as a String in a MongoDB database. We utilize Node.js as a platform. There are many ways you can preserve multiple checkbox values in React js inside the MongoDB database.

Step - 1: Install React.js

in the first step we will need to create a react fresh app.

npx create-react-app firstApp

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

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

Step - 3: Convert checked values into String.

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

So, indite 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.

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 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:8000/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

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

And finally, you can see your output in a web browser. now test it.

I hope you like this article.