React MERN Stack CRUD App Tutorial with Example
React MERN Stack Example
In this MERN stack tutorial, we will create a basic Student app from starting to finish. This app will allow us to create student, show students list, update student, and delete a student from the MongoDB database.
Before we move further let’s understand
What is MERN stack?
MERN Stack stands for MongoDB, Express, React, Node.js and this combined stack is known as MERN stack.
Stack | Detail |
---|---|
MongoDB | A document-oriented database programme based on NoSQL. |
Express | It’s a robust Node.js web application framework that helps in creating powerful REST APIs. |
React | A JavaScript library used to create beautiful and interactive user interfaces developed by Facebook and the community of individual developers. |
Node | It’s a JavaScript runtime environment built on Google Chrome’s V8 engine, and it compiles js at the runtime. |
Tutorial Objective
- Setting up React project
- Creating components in React
- Building and working with React routers
- Working with React-Bootstrap
- Getting started with React forms
- Consuming REST APIs in React app
- Getting started with Create, Read, Update and Delete in React
- Setting up a Node and Express server
- MongoDB set up in MERN stack project
- Creating REST APIs using Express.js
- Making HTTP requests with React Axios library
React MERN Stack CRUD Example
- Step 1: Prerequisite
- Step 2: Create React Application
- Step 3: Integrating React Bootstrap
- Step 4: Create Simple React Components
- Step 5: Implementing React Router
- Step 6: Create React Form with React Bootstrap
- Step 7: Submit Forms Data in React
- Step 8: Build Node JS Backend for MERN Stack
- Step 9: Setting up MongoDB Database
- Step 10: Define Mongoose Schema
- Step 11: Create Routes Express
- Step 12: Configure Server File
- Step 13: Make HTTP Requests with Axios
- Step 14: Show Data List with Axios
- Step 15: Edit, Update and Delete
- Step 16: Add Style in CRUD
Prerequisites
Before getting started with this tutorial, you must be aware of the fundamentals of React.js and HTML, CSS, JavaScript, TypeScript, or ES6. Check out React’s official website to know more about its features, central concepts, and API reference here.
In order to build MERN Stack web application, you must have Node.js installed on your system. Ignore this step if Node is already installed otherwise follow this step by step written article on how to install Node.js?
Once the Node is installed run below cmd to check the Node.js version:
node -v
Create React Application
Let’s start building the React project with create-react-app (CRA).
npx create-react-app react-mernstack-crud
Get inside the React project folder:
cd react-mernstack-crud
To start the React MERN Stack project, run following command:
npm start
This command opens the React project on the following URL: localhost:3000
Now, you are all set to build the React CRUD app!
Integrating React Bootstrap with React App
In the next step, we will install the React Bootstrap front-end framework in our MERN stack app. This framework will allow us to use the Bootstrap’s UI component in our React CRUD app.
React Bootstrap allows us to import individual UI components instead of importing the whole set of libraries.
npm install react-bootstrap bootstrap
You have to import the Bootstrap into src/App.js file and it will help you to create the UI components swiftly.
import "bootstrap/dist/css/bootstrap.css";
Creating Simple React Components
In this step, we will learn to create react components for managing data in the MERN stack CRUD application.
Head over to src
folder, make a folder and name it components
and within that directory create the following components.
- create-student.component.js
- edit-student.component.js
- student-list.component.js
Go to src/components/create-student.component.js
and add the following code.
import React, { Component } from "react";
export default class CreateStudent extends Component {
render() {
return (
<div>
<p>React Create Student Component!</p>
</div>
);
}
}
Go to src/components/edit-student.component.js
and add the following code.
import React, { Component } from "react";
export default class EditStudent extends Component {
render() {
return (
<div>
<p>React Edit Student Component!</p>
</div>
);
}
}
Go to src/components/student-list.component.js
and add the following code.
import React, { Component } from "react";
export default class StudentList extends Component {
render() {
return (
<div>
<p>React Student List Component!</p>
</div>
);
}
}
Implementing React Router
In this step, we will learn how to simply implement react router in React app.
Enter the command in terminal and hit enter to install the React Router version 5, please note this tutorial is not compatible with react-router version 6.
react-router-dom@5.3.0
You have to create the service-worker file, so create service worker file in the src folder and add the suggested code inside the src/serviceWorker.js file:
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service '
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all '
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: {
'Service-Worker': 'script'
},
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
Next, head over to src/index.js
file and tie the App component with the help of <BrowserRouter>
object.
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from "react-router-dom";
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
)
serviceWorker.unregister()
Next, include the menu in our React CRUD app. Add the given below code in the src/App.js
.
import React from 'react'
import Nav from 'react-bootstrap/Nav'
import Navbar from 'react-bootstrap/Navbar'
import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css'
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'
import CreateStudent from './components/create-student.component'
import EditStudent from './components/edit-student.component'
import StudentList from './components/student-list.component'
function App() {
return (
<div className="App">
<Router>
<header className="App-header">
<Navbar bg="dark" variant="dark">
<Container>
<Navbar.Brand>
<Link to={'/create-student'} className="nav-link">
React MERN Stack App
</Link>
</Navbar.Brand>
<Nav className="justify-content-end">
<Nav>
<Link to={'/create-student'} className="nav-link">
Create Student
</Link>
</Nav>
<Nav>
<Link to={'/student-list'} className="nav-link">
Student List
</Link>
</Nav>
</Nav>
</Container>
</Navbar>
</header>
<Container>
<Row>
<Col md={12}>
<div className="wrapper">
<Switch>
<Route
exact
path="/"
component={(props) => <CreateStudent {...props} />}
/>
<Route
exact
path="/create-student"
component={(props) => <CreateStudent {...props} />}
/>
<Route
exact
path="/edit-student/:id"
component={(props) => <EditStudent {...props} />}
/>
<Route
exact
path="/student-list"
component={(props) => <StudentList {...props} />}
/>
</Switch>
</div>
</Col>
</Row>
</Container>
</Router>
</div>
)
}
export default App
Create React Form with React Bootstrap
In this step, we will build the form using React Bootstrap front-end framework for submitting the Student data in the create-student.component.js
component.
import React, {Component} from "react";
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button';
export default class CreateStudent extends Component {
render() {
return (<div class="form-wrapper">
<Form>
<Form.Group controlId="Name">
<Form.Label>Name</Form.Label>
<Form.Control type="text"/>
</Form.Group>
<Form.Group controlId="Email">
<Form.Label>Email</Form.Label>
<Form.Control type="email"/>
</Form.Group>
<Form.Group controlId="Name">
<Form.Label>Roll No</Form.Label>
<Form.Control type="text"/>
</Form.Group>
<Button variant="danger" size="lg" block="block" type="submit">
Create Student
</Button>
</Form>
</div>);
}
}
Submit Forms Data in React
Next, we will learn to submit the Forms data in React.js. We have already created the Student form, and need to submit student’s: Name, Email and Roll No to the database.
We will start by creating the constructor inside the CreateStudent component class. Then set the initial state of the CreateStudent component by setting this.state
Object.
Then declare the various functions with every React form field value, so when the user inserts the data within the form input field, a state will be set accordingly.
Next, we need to define the submit event, which will allow us to create new student data when the user clicks on `Create Student`
submit button.
import React, { Component } from "react";
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button';
import axios from 'axios';
export default class CreateStudent extends Component {
constructor(props) {
super(props)
// Setting up functions
this.onChangeStudentName = this.onChangeStudentName.bind(this);
this.onChangeStudentEmail = this.onChangeStudentEmail.bind(this);
this.onChangeStudentRollno = this.onChangeStudentRollno.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// Setting up state
this.state = {
name: '',
email: '',
rollno: ''
}
}
onChangeStudentName(e) {
this.setState({ name: e.target.value })
}
onChangeStudentEmail(e) {
this.setState({ email: e.target.value })
}
onChangeStudentRollno(e) {
this.setState({ rollno: e.target.value })
}
onSubmit(e) {
e.preventDefault()
const studentObject = {
name: this.state.name,
email: this.state.email,
rollno: this.state.rollno
};
axios.post('http://localhost:4000/students/create-student', studentObject)
.then(res => console.log(res.data));
this.setState({ name: '', email: '', rollno: '' })
}
render() {
return (<div className="form-wrapper">
<Form onSubmit={this.onSubmit}>
<Form.Group controlId="Name">
<Form.Label>Name</Form.Label>
<Form.Control type="text" value={this.state.name} onChange={this.onChangeStudentName} />
</Form.Group>
<Form.Group controlId="Email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" value={this.state.email} onChange={this.onChangeStudentEmail} />
</Form.Group>
<Form.Group controlId="Name">
<Form.Label>Roll No</Form.Label>
<Form.Control type="text" value={this.state.rollno} onChange={this.onChangeStudentRollno} />
</Form.Group>
<Button variant="danger" size="lg" block="block" type="submit" className="mt-4">
Create Student
</Button>
</Form>
</div>);
}
}
Build Node JS Backend for MERN Stack
We will create a folder inside our React app to manage the `backend`
services such as database, models, schema, routes and APIs, name this folder backend.
Run command to create backend folder and get inside of it.
mkdir backend && cd backend
Then, we need to create a separate package.json
file for managing the backend of our React CRUD demo app example.
npm init
Next, install the given below Node dependencies for MERN stack backend.
npm install mongoose express cors body-parser
NPM | Detail |
---|---|
Express | It’s a robust Node.js web application framework that helps in creating powerful REST APIs. |
MongoDB | It’s a NoSQL document-oriented database for creating a robust web application. |
CORS | It’s a node.js package helps in enabling Access-Control-Allow-Origin CORS header. |
bodyParser | This package extracts the entire body portion of an incoming request stream and exposes it on req.body. |
Install the nodemon dependency to automate the server restarting process.
npm install nodemon --save-dev
Define Mongoose Schema
Then, create a mongoDB schema for interacting with mongoDB database. Create a folder inside backend folder to keep schema related files and name it Models
and create a file Student.js
inside of it.
mkdir Models && cd Models && touch Student.js
Next, include the following code in backend/models/Student.js
file:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let studentSchema = new Schema({
name: {
type: String
},
email: {
type: String
},
rollno: {
type: Number
}
}, {
collection: 'students'
})
module.exports = mongoose.model('Student', studentSchema)
We declared a name, email and rollno fields along with their respective data types in student Schema.
Create Routes Using Express/Node JS for React CRUD App
In this step, we are building routes (REST APIs) for React CRUD CREATE, READ, UPDATE and DELETE app using Express and Node.js. These routes will help us to manage the data in our React MERN stack student app.
Create a folder and name it routes, here we will keep all the routes related files. Also, create the student.routes.js
file inside this folder in this file we will define REST APIs.
mkdir routes && cd routes && touch student.route.js
Then, go to backend/routes/student.route.js
file and add the following code.
let mongoose = require('mongoose'),
express = require('express'),
router = express.Router();
// Student Model
let studentSchema = require('../models/Student');
// CREATE Student
router.route('/create-student').post((req, res, next) => {
studentSchema.create(req.body, (error, data) => {
if (error) {
return next(error)
} else {
console.log(data)
res.json(data)
}
})
});
// READ Students
router.route('/').get((req, res) => {
studentSchema.find((error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
// Get Single Student
router.route('/edit-student/:id').get((req, res) => {
studentSchema.findById(req.params.id, (error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
// Update Student
router.route('/update-student/:id').put((req, res, next) => {
studentSchema.findByIdAndUpdate(req.params.id, {
$set: req.body
}, (error, data) => {
if (error) {
return next(error);
console.log(error)
} else {
res.json(data)
console.log('Student updated successfully !')
}
})
})
// Delete Student
router.route('/delete-student/:id').delete((req, res, next) => {
studentSchema.findByIdAndRemove(req.params.id, (error, data) => {
if (error) {
return next(error);
} else {
res.status(200).json({
msg: data
})
}
})
})
module.exports = router;
Configure Server File
We have almost created everything to set up the Node and Express.js backend for React MERN Stack CRUD app. Now we will create the index.js
file in the root of the backend folder.
Run command from the root of the backend folder to create index.js
file.
touch index.js
Paste the following code inside the backend/index.js
file.
let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');
// Express Route
const studentRoute = require('../backend/routes/student.route')
// Connecting mongoDB Database
mongoose
.connect('mongodb://127.0.0.1:27017/mydatabase')
.then((x) => {
console.log(`Connected to Mongo! Database name: "${x.connections[0].name}"`)
})
.catch((err) => {
console.error('Error connecting to mongo', err.reason)
})
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.use('/students', studentRoute)
// PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
console.log('Connected to port ' + port)
})
// 404 Error
app.use((req, res, next) => {
next(createError(404));
});
app.use(function (err, req, res, next) {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
Now, we have created the backend for our MERN stack app. Open the terminal and run the command to start MongoDB, It will allow you to save the student data in the database.
mongod
Also, open another terminal and run the following command to start the Nodemon server by staying in the backend folder.
cd backend && nodemon
Following will be your APIs routes created with Express.js, MongoDB and Node.js.
REST API | URL |
---|---|
GET | http://localhost:4000/students |
POST | /students/create-student |
GET | /students/edit-student/id |
PUT | /students/update-student/id |
DELETE | /students/delete-student/id |
You can also test these APIs in Postmen API development tool, click here to download Postmen.
Using Axios with React to Make HTTP Request
In this step, we will learn to use the Axios library in React MERN Stack app to handle the HTTP request. Axios is a promise-based HTTP client for the browser and node.js. It offers the following features.
- Make XMLHttpRequests from the browser
- Handle http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Self-regulating for JSON data
- Client-side protection from XSRF
Run command in the terminal to install axios in React CRUD app.
npm install axios
Next, we will send the student’s data to the MongoDB server as an object using the Axios post http method.
Add the following code in src/components/create-student.component.js file:
import React, { Component } from "react";
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button';
import axios from 'axios';
export default class CreateStudent extends Component {
constructor(props) {
super(props)
// Setting up functions
this.onChangeStudentName = this.onChangeStudentName.bind(this);
this.onChangeStudentEmail = this.onChangeStudentEmail.bind(this);
this.onChangeStudentRollno = this.onChangeStudentRollno.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// Setting up state
this.state = {
name: '',
email: '',
rollno: ''
}
}
onChangeStudentName(e) {
this.setState({ name: e.target.value })
}
onChangeStudentEmail(e) {
this.setState({ email: e.target.value })
}
onChangeStudentRollno(e) {
this.setState({ rollno: e.target.value })
}
onSubmit(e) {
e.preventDefault()
const studentObject = {
name: this.state.name,
email: this.state.email,
rollno: this.state.rollno
};
axios.post('http://localhost:4000/students/create-student', studentObject)
.then(res => console.log(res.data));
this.setState({ name: '', email: '', rollno: '' })
}
render() {
return (<div className="form-wrapper">
<Form onSubmit={this.onSubmit}>
<Form.Group controlId="Name">
<Form.Label>Name</Form.Label>
<Form.Control type="text" value={this.state.name} onChange={this.onChangeStudentName} />
</Form.Group>
<Form.Group controlId="Email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" value={this.state.email} onChange={this.onChangeStudentEmail} />
</Form.Group>
<Form.Group controlId="Name">
<Form.Label>Roll No</Form.Label>
<Form.Control type="text" value={this.state.rollno} onChange={this.onChangeStudentRollno} />
</Form.Group>
<Button variant="danger" size="lg" block="block" type="submit" className="mt-4">
Create Student
</Button>
</Form>
</div>);
}
}
Then enter the student name, email and rollno and click on Create Student button and your data will be saved in MongoDB NoSQL database.
Show Data List with React Axios
In this step, we will show the student’s data list using React Axios and react bootstrap. Add the given below code inside the src/components/student-list.component.js
.
import React, { Component } from "react";
import axios from 'axios';
import Table from 'react-bootstrap/Table';
import StudentTableRow from './StudentTableRow';
export default class StudentList extends Component {
constructor(props) {
super(props)
this.state = {
students: []
};
}
componentDidMount() {
axios.get('http://localhost:4000/students/')
.then(res => {
this.setState({
students: res.data
});
})
.catch((error) => {
console.log(error);
})
}
DataTable() {
return this.state.students.map((res, i) => {
return <StudentTableRow obj={res} key={i} />;
});
}
render() {
return (<div className="table-wrapper">
<Table striped bordered hover>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Roll No</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.DataTable()}
</tbody>
</Table>
</div>);
}
}
In the above code, we are making HTTP GET request using React Axios and Node/Express JS REST API. We are using React-Bootstrap table to show the Students data on the frontend.
In the next step, we will create the component and name it StudentTableRow.js and keep it in the components folder. We have already imported the component in the student-list.component.js file. Then add the given below code inside the components/StudentTableRow.js
file.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Button from 'react-bootstrap/Button';
export default class StudentTableRow extends Component {
render() {
return (
<tr>
<td>{this.props.obj.name}</td>
<td>{this.props.obj.email}</td>
<td>{this.props.obj.rollno}</td>
<td>
<Link className="edit-link" to={"/edit-student/" + this.props.obj._id}>
Edit
</Link>
<Button size="sm" variant="danger">Delete</Button>
</td>
</tr>
);
}
}
Edit, Update and Delete Data in React
In this step, we will create edit and update functionality for the user to manage the student data in React v16.9.0. We used the Axios library and making the PUT request to update the data in MongoDB database using REST API built with Node and Express JS. Include the given below code inside the edit-student.component.js
file.
import React, { Component } from "react";
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button';
import axios from 'axios';
export default class EditStudent extends Component {
constructor(props) {
super(props)
this.onChangeStudentName = this.onChangeStudentName.bind(this);
this.onChangeStudentEmail = this.onChangeStudentEmail.bind(this);
this.onChangeStudentRollno = this.onChangeStudentRollno.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// State
this.state = {
name: '',
email: '',
rollno: ''
}
}
componentDidMount() {
axios.get('http://localhost:4000/students/edit-student/' + this.props.match.params.id)
.then(res => {
this.setState({
name: res.data.name,
email: res.data.email,
rollno: res.data.rollno
});
})
.catch((error) => {
console.log(error);
})
}
onChangeStudentName(e) {
this.setState({ name: e.target.value })
}
onChangeStudentEmail(e) {
this.setState({ email: e.target.value })
}
onChangeStudentRollno(e) {
this.setState({ rollno: e.target.value })
}
onSubmit(e) {
e.preventDefault()
const studentObject = {
name: this.state.name,
email: this.state.email,
rollno: this.state.rollno
};
axios.put('http://localhost:4000/students/update-student/' + this.props.match.params.id, studentObject)
.then((res) => {
console.log(res.data)
console.log('Student successfully updated')
}).catch((error) => {
console.log(error)
})
// Redirect to Student List
this.props.history.push('/student-list')
}
render() {
return (<div className="form-wrapper">
<Form onSubmit={this.onSubmit}>
<Form.Group controlId="Name">
<Form.Label>Name</Form.Label>
<Form.Control type="text" value={this.state.name} onChange={this.onChangeStudentName} />
</Form.Group>
<Form.Group controlId="Email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" value={this.state.email} onChange={this.onChangeStudentEmail} />
</Form.Group>
<Form.Group controlId="Name">
<Form.Label>Roll No</Form.Label>
<Form.Control type="text" value={this.state.rollno} onChange={this.onChangeStudentRollno} />
</Form.Group>
<Button variant="danger" size="lg" block="block" type="submit">
Update Student
</Button>
</Form>
</div>);
}
}
Make Axios Delete Request to Delete Data
Lastly, we will be building the delete functionality in our React CRUD demo app. Go to components/StudentTableRow.js
file and call the Node/Express API to delete the student data from the MongoDB database.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Button from 'react-bootstrap/Button';
export default class StudentTableRow extends Component {
constructor(props) {
super(props);
this.deleteStudent = this.deleteStudent.bind(this);
}
deleteStudent() {
axios.delete('http://localhost:4000/students/delete-student/' + this.props.obj._id)
.then((res) => {
console.log('Student successfully deleted!')
}).catch((error) => {
console.log(error)
})
}
render() {
return (
<tr>
<td>{this.props.obj.name}</td>
<td>{this.props.obj.email}</td>
<td>{this.props.obj.rollno}</td>
<td>
<Link className="edit-link" to={"/edit-student/" + this.props.obj._id}>
Edit
</Link>
<Button onClick={this.deleteStudent} size="sm" variant="danger">Delete</Button>
</td>
</tr>
);
}
}
Style CRUD App
In this step, you have to style the crud application by adding the custom CSS in src/App.css file:
.wrapper {
padding-top: 30px;
}
body h3 {
margin-bottom: 25px;
}
.navbar-brand a {
color: #ffffff;
}
.form-wrapper,
.table-wrapper {
max-width: 500px;
margin: 0 auto;
}
.table-wrapper {
max-width: 700px;
}
.edit-link {
padding: 7px 10px;
font-size: 0.875rem;
line-height: normal;
border-radius: 0.2rem;
color: #fff;
background-color: #28a745;
border-color: #28a745;
margin-right: 10px;
position: relative;
top: 1px;
}
.edit-link:hover {
text-decoration: none;
color: #ffffff;
}
Conclusion
Finally, we have completed React MERN Stack CRUD web app tutorial. In this tutorial, we learned how to create a basic React CRUD app, set up React-Bootstrap, and how to use its ready-made UI components in React app.
We also learned to develop Backend server using Node and Express JS from scratch. I hope you enjoyed reading this article if you found any bug in this tutorial kindly report here. Please click on the below button to download the React MERN stack project code from GitHub.