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.
First of all, let us install React.js using the following command.
npx create-react-app checkbox
We need to install the Bootstrap and axios libraries inside the folder.
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.
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
I am 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.
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. When the user either checks the checkbox or uncheck the checkbox, the state will be changed.
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.
We will save the string into the database. The String is a comma-separated value. So, we filter the state, and if any checkbox value is right or true, we add it to an array and then finally change that array into the string and send that data to the Node.js server.
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()
};
}
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.
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;
Start the mongodb server using the following command.
mongodb
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
Now you have three servers running.
Go to the browser and navigate to this URL: http://localhost:3000/
Thanks for reading !!!
#react js #mongodb #node.js #react