Open In App

How To Build a Basic CRUD App With Node and React ?

Last Updated : 07 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will create a basic Student app from scratch using the MERN stack which will implement all the CRUD(Create, Read, Update and Delete) Operations.

Preview of final output:

OutputMernstudent

App functionality

  • Create a new student (CREATE)
  • Update an existing student (UPDATE)
  • Show all students list (READ)
  • Delete a student (DELETE)

REST API in this project

REST API Request

URL

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

Step 1: Initialize React App for Front End

Let’s start building the Front-end part with React. To create a new React App, enter the following code into terminal and hit enter. 

npx create-react-app mern-stack-crud

Step 2: Switch to Project Directory

Move into the React project folder.

cd mern-stack-crud

Step 3: Run The Frontend

To run the React App, run the following command:

npm start

This command opens the React App to the browser on the following URL: http://localhost:3000/

Step 4:  Install Required Modules

To build the React App we need to install some external modules. 

NPM

Detail

React-BootstrapReact-Bootstrap has evolved and grown alongside React, making it an excellent choice for your UI.
React-Router-DomReact Router DOM enables you to implement routing in a React App. 
AxiosIt is a promise base HTTP Client and use for network request.
FormikA great library to build form in React.
YupYup is a JavaScript schema builder for form validation.

To install, run the following code on the terminal. 

npm i react-bootstrap@next bootstrap@5.1.0 react-router-dom axios formik yup

Step 5: Creating Simple React Components

In this step we will create some React Components to manage student data.

Head over to src folder, make a folder and name it Components and within that directory create the following components.

  • StudentForm.js – Reusable Student form
  • create-student.component.js – Responsible for create new student 
  • edit-student.component.js – Responsible for update student data
  • student-list.component.js – Responsible for display all student
  • StudentTableRow.js  – Responsible for display a single student 

Frontend Project Structure:

front-end project structure

Dependencies

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.2",
"body-parser": "^1.20.2",
"bootstrap": "^5.1.0",
"cors": "^2.8.5",
"express": "^4.19.2",
"formik": "^2.4.6",
"mongoose": "^8.5.1",
"nodemon": "^3.1.4",
"react": "^18.3.1",
"react-bootstrap": "^2.9.0-beta.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.25.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"yup": "^1.4.0"
}

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.

Example: This example creates frontend for Student database app including a student form and table to display data.

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 {
    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;
}

/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

/* Firefox */
input[type=number] {
    -moz-appearance: textfield;
}
JavaScript JavaScript JavaScript JavaScript JavaScript JavaScript

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

Output

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

ExpressNode.js framework that helps in creating powerful REST APIs.
body-parserExtracts the entire body portion of a request stream and exposes it on req.body.
corsIt’s a Node.js package that helps in enabling Access-Control-Allow-Origin CORS header.
mongooseIt’s a NoSQL database for creating a robust web application.

To install the above dependencies, run the following code on the terminal. 

npm install express body-parser cors mongoose nodemon dotenv

Backend Project Structure:

er

Folder Structure

Dependencies

"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"mongoose": "^8.5.1",
"nodemon": "^3.1.4"
}

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.

Example: This example uses mongo and node, express to setup the backend.

JavaScript
// 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

// Import Express Routes
const studentRoute = require('../backend/routes/student.route');

// Load environment variables from .env file
const { MONGODB_URI, PORT } = process.env;

// Connecting to MongoDB Database
mongoose.connect('Your Connection String', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
    .then(() => {
        console.log('Database successfully connected!');
    })
    .catch((error) => {
        console.log('Could not connect to database: ' + error);
    });

// Initialize Express app
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use('/students', studentRoute);

// Define the PORT
const port = PORT || 4000;

// Start the server
app.listen(port, () => {
    console.log('Connected to port ' + port);
});

// Handle 404 errors
app.use((req, res, next) => {
    res.status(404).send('Error 404: Not Found!');
});

// Global error handler
app.use((err, req, res, next) => {
    console.error(err.message);
    const status = err.statusCode || 500;
    res.status(status).send(err.message);
});
JavaScript JavaScript

Now, we have successfully created the backend for our mern-stack-app.  

Open a terminal and run the following command to start the Nodemon server by staying in the backend folder.

npm start

Output:

Summary

This article 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.



Next Article

Similar Reads

three90RightbarBannerImg