In this article, we would like to inform you that how to create react crud example with node js rest API example. ReactJs is an open-source JavaScript library and it is developed by Facebook. react js can be used to make a single-page application(SPA). ReactJS is also used to reuse UI components and run without reloading application so it is scalable, simple, and fast.
So, you can follow the below steps for creating a react crud example.
In this step, if you want to create a react application then you can follow below Url for install react js.
npx create-react-app react_crud cd react_crud
now, After the installation of react js, you can install the bootstrap using the below command.
npm install bootstrap --save
here, we will import the bootstrap in the app.js file, so you can see the below code.
src/app.js
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Create from './components/create.component';
import Edit from './components/edit.component';
import Index from './components/index.component';
class App extends Component {
render() {
return (
<Router>
<div className="container">
<h2 style={{ textAlign: "center" }}>Welcome to React CRUD Tutorial</h2> <br/>
<Switch>
<Route exact path='/' component={Index} />
<Route exact path='/create' component={ Create } />
<Route path='/edit/:id' component={ Edit } />
</Switch>
</div>
</Router>
);
}
}
export default App;
The below command using install the react route. so you can follow the below command.
npm install react-router-dom --save
Go to the index.js file and Modify the below code.
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
serviceWorker.unregister();
here in this step, we will create three components, like index, create, and edit. so you can see the below code.
src/components/index.component.js
import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';
import { Link } from 'react-router-dom';
export default class Index extends Component {
constructor(props) {
super(props);
this.state = {students:[]};
}
componentDidMount(){
axios.get('http://localhost:4000/students')
.then(response => {
this.setState({ students: response.data.result });
})
.catch(function (error) {
console.log(error);
})
}
tabRow(){
return this.state.students.map(function(object, i){
return <TableRow obj={object} key={i} />;
});
}
render() {
return (
<div>
<div class="row">
<div class="col-lg-10"><h3 align="center">Student List</h3></div>
<div class="col-lg-2"><Link to={'/create'} className="nav-link">Create Student</Link></div>
</div>
<table className="table table-striped" style={{ marginTop: 20 }}>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Mobile</th>
<th colSpan="2">Action</th>
</tr>
</thead>
<tbody>
{ this.tabRow() }
</tbody>
</table>
</div>
);
}
}
src/components/TableRow.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
class TableRow extends Component {
constructor(props) {
super(props);
this.delete = this.delete.bind(this);
}
delete() {
axios.delete('http://localhost:4000/student/delete', {
id: this.props.obj.id
})
.then( (response)=> {
this.props.history.push('/');
})
.catch(function (error) {
});
}
render() {
return (
<tr>
<td>
{this.props.obj.first_name}
</td>
<td>
{this.props.obj.last_name}
</td>
<td>
{this.props.obj.email}
</td>
<td>
{this.props.obj.mobile}
</td>
<td>
<Link to={"/edit/"+this.props.obj.id} className="btn btn-primary">Edit</Link>
</td>
<td>
<button onClick={this.delete} className="btn btn-danger">Delete</button>
</td>
</tr>
);
}
}
export default TableRow;
src/components/create.component.js
import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
export default class Create extends Component {
constructor(props) {
super(props);
this.onChangeFirstName = this.onChangeFirstName.bind(this);
this.onChangeLastName = this.onChangeLastName.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangeMobile = this.onChangeMobile.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
first_name: '',
last_name: '',
email: '',
mobile:'',
redirect: true
}
}
onChangeFirstName(e) {
this.setState({
first_name: e.target.value
});
}
onChangeLastName(e) {
this.setState({
last_name: e.target.value
})
}
onChangeEmail(e) {
this.setState({
email: e.target.value
})
}
onChangeMobile(e) {
this.setState({
mobile: e.target.value
})
}
onSubmit(e) {
e.preventDefault();
axios.post('http://localhost:4000/student/add', {
first_name: this.state.first_name,
last_name: this.state.last_name,
email: this.state.email,
mobile: this.state.mobile
})
.then( (response)=> {
this.props.history.push('/');
})
.catch(function (error) {
});
}
render() {
return (
<div style={{ marginTop: 10 }}>
<div class="row">
<div class="col-lg-10"><h3 align="center">Add New Student</h3></div>
<div class="col-lg-2"><Link to={'/'} className="nav-link">Back</Link></div>
</div>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>First Name: </label>
<input type="text" className="form-control" value={this.state.first_name} onChange={this.onChangeFirstName} />
</div>
<div className="form-group">
<label>Last Name: </label>
<input type="text" className="form-control" value={this.state.last_name} onChange={this.onChangeLastName} />
</div>
<div className="form-group">
<label>Email : </label>
<input type="text" className="form-control" value={this.state.email} onChange={this.onChangeEmail} />
</div>
<div className="form-group">
<label>Mobile: </label>
<input type="text" className="form-control" value={this.state.mobile} onChange={this.onChangeMobile} />
</div>
<div className="form-group">
<input type="submit" value="Register Student" className="btn btn-primary"/>
</div>
</form>
</div>
)
}
}
src/components/edit.component.js
import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
export default class Edit extends Component {
constructor(props) {
super(props);
this.onChangeFirstName = this.onChangeFirstName.bind(this);
this.onChangeLastName = this.onChangeLastName.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangeMobile = this.onChangeMobile.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
first_name: '',
last_name: '',
email: '',
mobile:''
}
}
componentDidMount() {
axios.get('http://localhost:4000/student/'+this.props.match.params.id)
.then(response => {
this.setState({
first_name: response.data.result.first_name,
last_name: response.data.result.last_name,
email: response.data.result.email,
mobile: response.data.result.mobile });
})
.catch(function (error) {
console.log(error);
})
}
onChangeFirstName(e) {
this.setState({
first_name: e.target.value
});
}
onChangeLastName(e) {
this.setState({
last_name: e.target.value
})
}
onChangeEmail(e) {
this.setState({
email: e.target.value
})
}
onChangeMobile(e) {
this.setState({
mobile: e.target.value
})
}
onSubmit(e) {
e.preventDefault();
axios.put('http://localhost:4000/student/update', {
id: this.props.match.params.id,
first_name: this.state.first_name,
last_name: this.state.last_name,
email: this.state.email,
mobile: this.state.mobile
})
.then( (response)=> {
this.props.history.push('/');
})
.catch(function (error) {
});
}
render() {
return (
<div style={{ marginTop: 10 }}>
<div class="row">
<div class="col-lg-10"><h3 align="center">Update Student</h3></div>
<div class="col-lg-2"><Link to={'/'} className="nav-link">Back</Link></div>
</div>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>First Name: </label>
<input type="text" className="form-control" value={this.state.first_name} onChange={this.onChangeFirstName} />
</div>
<div className="form-group">
<label>Last Name: </label>
<input type="text" className="form-control" value={this.state.last_name} onChange={this.onChangeLastName} />
</div>
<div className="form-group">
<label>Email : </label>
<input type="text" className="form-control" value={this.state.email} onChange={this.onChangeEmail} />
</div>
<div className="form-group">
<label>Mobile: </label>
<input type="text" className="form-control" value={this.state.mobile} onChange={this.onChangeMobile} />
</div>
<div className="form-group">
<input type="submit" value="Update Student" className="btn btn-primary"/>
</div>
</form>
</div>
)
}
}
now here we are configuring the node js server, so you can see the below file. if you want additional information then you can visit our article node js crud example with mysql.
server.js
var express = require('express');
var app = express();
var dbConn = require('./config');
var bodyParser = require('body-parser');
var dateTime = require('node-datetime');
var dt = dateTime.create();
var curdate = dt.format('Y-m-d H:M:S');
const cors = require('cors');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.get('/', function (req, res) {
console.log('hello world');
});
// Retrieve all students data
app.get('/students', function (req, res) {
dbConn.query('SELECT * FROM students', function (err, results) {
if(err) {
throw err;
} else {
return res.send({ status: true, result: results});
}
});
});
// Retrieve the specific student data
app.get('/student/:id', function (req, res) {
let student_id = req.params.id;
if(!student_id) {
return res.status(400).send({ status: false, message: 'Please provide student id' });
}
dbConn.query('SELECT * FROM students where id=?', student_id, function (err, result) {
if(err) {
throw err;
} else {
return res.send({ status: true, result: result[0]});
}
});
});
// Add the student data
app.post('/student/add', function (req, res) {
var student = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
mobile: req.body.mobile,
created_at: curdate
}
if (!student) {
return res.status(400).send({ status:false, message: 'Please Provide Student Data' });
}
dbConn.query("INSERT INTO students SET ? ", student, function (err, results) {
if(err) {
throw err;
} else {
return res.send({ status: true, result: results, message: 'New student has been created successfully.' });
}
});
});
// Update the student data
app.put('/student/update', function (req, res) {
var student_id = req.body.id;
var student = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
mobile: req.body.mobile,
created_at: curdate
}
if (!student_id || !student) {
return res.status(400).send({ status: false, message: 'Please provide student data and student id' });
}
dbConn.query("UPDATE students SET ? WHERE id = ?", [student, student_id], function (err, results) {
if(err) {
throw err;
} else {
return res.send({ status: true, result: results, message: 'Student has been updated successfully.' });
}
});
});
// Delete the student data
app.delete('/student/delete', function (req, res) {
let student_id = req.body.id;
if (!student_id) {
return res.status(400).send({ status: false, message: 'Please provide student id' });
}
dbConn.query('DELETE FROM students WHERE id = ?', [student_id], function (err, results) {
if(err) {
throw err;
} else {
return res.send({ status: true, result: results, message: 'Student has been deleted successfully.' });
}
});
});
app.listen(4000, function(){
console.log('Server running at port 3000: http://localhost:4000');
});
If you want to run the application then you can follow the below command. if you any change in your app then use the npm run build and after you can run the application.
cd my-app npm start
Now we will run our application using the below Url in the browser.
http://127.0.0.1:3000