Mango Build a Basic CRUD App With Node and React
Mango Build a Basic CRUD App With Node and React
Create a basic Student app from scratch using the MERN stack which will
implement all the CRUD (Create, Read, Update and Delete) Operations.
This Project creates a Student database application using MERN (Mongo, Express,
React, Node) to show the Basic CRUD Operations in a MERN App. It uses the api
endpoints for HTTP requests like GET, POST, PUT, DELETE to create, read,
update and detele the student data in the mongo database.
App functionality
Create a new student (CREATE)
Update an existing student (UPDATE)
Show all students list (READ)
Delete a student (DELETE)
GET http://localhost:4000/students
GET /students/students/id
POST /students/students
PUT /students/students/id
DELETE /students/students/id
Building a basic CRUD app with Node and React is a perfect way to learn full-stack
development.
Now, first of all, we will work on the frontend part of our application using React.js.
Steps to Create React Application and Installing modules
Approach
For the Frontend of this Student database App
We will build a reusable student form with Formik and React-Bootstrap. This form has all
the necessary fields to enter student details. We have also made client-side form validation
with Yup. In the future, we will use this component for creating and update a student. Go
to src/Components/StudentForm.js.
We will create a component to add a new student. We have already created
a StudentForm component to enter student details. Now, it’s time to use this component.
Go to src/Components/create-student.component.js.
We will create a component to update details. We have reusable StudentForm component,
let’s use it again. We will fetch student details to reinitialise form. Go
to src/Components/edit-student.component.js.
We will build a component to display the student details in a table. We will fetch student’s
data and iterate over it to create table row for every student. Go
to src/Components/student-list.component.js.
We will return table row which is responsible to display student data. Go
to src/Components/StudentTableRow.js.
Finally, include the menu to make routing in our MERN Stack CRUD app. Go
to src/App.js and write the following code.
This example creates frontend for Student database app including a student
form and table to display data.
//App.js
// Import React
import React from "react";
// Import Bootstrap
import { Nav, Navbar, Container, Row, Col }
from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.css";
<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={CreateStudent} />
<Route path="/create-student"
component={CreateStudent} />
<Route path="/edit-student/:id"
component={EditStudent} />
<Route path="/student-list"
component={StudentList} />
</Switch>
</div>
</Col>
</Row>
</Container>
</div>
</Router>
);
};
// src/Components/create-student.component.js
// Import Modules
import React,
useState,
useEffect
} from "react";
import StudentForm
from "./StudentForm";
// CreateStudent Component
useState(
{
name: '',
email: '',
rollno: ''
})
// onSubmit handler
const onSubmit =
studentObject => {
axios.post(
'http://localhost:4000/students/students',
studentObject)
.then(res => {
else
Promise.reject()
})
return (
<StudentForm initialValues={formValues}
onSubmit={onSubmit}
enableReinitialize>
Create Student
</StudentForm>
}
// Export CreateStudent Component
//src/Components/edit-student.component.js
// Import Modules
import React,
useState,
useEffect
} from "react";
import StudentForm
from "./StudentForm";
// EditStudent Component
useState(
name: "",
email: "",
rollno: "",
);
//onSubmit handler
axios
.put(
"http://localhost:4000/students/students/" +
props.match.params.id,
studentObject
.then((res) => {
props.history.push("/student-list");
} else Promise.reject();
})
.catch(
(err) =>
);
};
useEffect(() => {
axios
.get(
"http://localhost:4000/students/update-student/"
+ props.match.params.id
.then((res) => {
const {
name,
email,
rollno
} = res.data;
setFormValues(
name,
email,
rollno
});
})
.catch(
(err) =>
console.log(err)
);
}, []);
return (
<StudentForm
initialValues={formValues}
onSubmit={onSubmit}
enableReinitialize>
Update Student
</StudentForm>
);
};
//src/Components/student-list.component.js
useEffect(() => {
axios
.get("http://localhost:4000/students/")
setStudents(data);
})
.catch((error) => {
console.log(error);
});
}, []);
return <StudentTableRow
obj={res} key={i} />;
});
};
return (
<div className="table-wrapper">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Roll No</th>
<th>Action</th>
</tr>
</thead>
<tbody>{DataTable()}</tbody>
</Table>
</div>
);
};
StudentTableRow.js
//src/Components/StudentTableRow.js
const StudentTableRow =
(props) => {
const {
_id,
name,
email,
rollno
} = props.obj;
axios
.delete(
"http://localhost:4000/students/students/" + _id)
.then((res) => {
window.location.reload();
} else Promise.reject();
})
.catch(
(err) =>
};
return (
<tr>
<td>{name}</td>
<td>{email}</td>
<td>{rollno}</td>
<td>
<Link className="edit-link"
to={"/edit-student/" + _id}>
Edit
</Link>
<Button
onClick={deleteStudent}
size="sm" variant="danger">
Delete
</Button>
</td>
</tr>
);
};
CSS
/* App.css */
.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 {
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;
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
Now, we have successfully created the frontend for our mern-stack-app. Let’s build the
backend part. Before, jumping to next section take a look how the frontend part working
without backend.
Step to Run the application: Open the terminal and type the following command.
npm start
Back end
Steps to Setup the Backend
Step 1: Create Backend Directory
Run command to create backend folder for server and get inside of it.
mkdir backend
cd backend
Step 2: Initialize Backend Project
Create package.json – Next, we need to create a separate package.json file for managing the
server of our mern-stack-crud app.
npm init -y
Step 3: Install Node Dependencies
Install the following Node dependencies.
NPM Detail
To install the above dependencies, run the following code on the terminal.
npm install express body-parser cors mongoose nodemon dotenv
Approach
For backend of Student database app
We will set up a MongoDB database for our app. Before, starting make sure you have latest
version of MongoDB is installed on your system. Create folder inside the backend folder
and name it database. Create a file by the name of db.js inside the database folder. Go
to backend/database/db.js. We have declared the MongoDB database and name
it reactdb.
Now, create MongoDB schema for interacting with MongoDB database. Create a folder
called models inside backend folder to keep schema related files and create a
file Student.js inside of it to define MongoDB schema. Go
to backend/models/Student.js.
We are set up some routes (REST APIs) for CREATE, READ, UPDATE and DELETE
using Express and Node.js. These routes will help us to manage the data in our mern-
stack-crud app.
We have almost created everything for our mern-stack-crud app. Now, create
the server.js file in the root of the backend folder. Go to backend/server.js and write the
following code.
// server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config(); // For loading environment variables
// backend/routes/student.route.js
const express = require('express');
const router = express.Router();
const Student = require('../models/Student'); // Student Model
// CREATE Student
router.post('/students', async (req, res, next) => {
try {
const data = await Student.create(req.body);
console.log(data);
res.json(data);
} catch (error) {
return next(error);
}
});
// READ Students
router.get('/', async (req, res, next) => {
try {
const data = await Student.find();
res.json(data);
} catch (error) {
return next(error);
}
});
// UPDATE Student
router.route('/students/:id')
// Get Single Student
.get(async (req, res, next) => {
try {
const data = await Student.findById(req.params.id);
res.json(data);
} catch (error) {
return next(error);
}
})
// Update Student Data
.put(async (req, res, next) => {
try {
const data = await Student.findByIdAndUpdate(req.params.id, {
$set: req.body,
}, { new: true });
res.json(data);
console.log("Student updated successfully!");
} catch (error) {
return next(error);
}
});
// DELETE Student
router.delete('/students/:id', async (req, res, next) => {
try {
const data = await Student.findByIdAndRemove(req.params.id);
res.status(200).json({
msg: data,
});
} catch (error) {
return next(error);
}
});
module.exports = router;
Output
This Project creates a Student database application using MERN (Mongo,
Express, React, Node) to show the Basic CRUD Operations in a MERN App.
It uses the api endpoints for HTTP requests like GET, POST, PUT, DELETE
to create, read, update and detele the student data in the mongo database.