React Tutorial- React MERN Stack CRUD App Example

Learn to Build React CRUD Web Application in this React tutorial; We will also learn to set up a Node Server and create REST APIs using Node and Express.js.

 

React MERN Stack Example

In this MERN Stack tutorial, we will create a basic app that will allow us to create a student list and show it, update the student list and delete a student from the MongoDB database.

 

What is MERN Stack?

MERN Stack stands for MongoDB, Express, React, Node.js and this combined stack is called MERN Stack.

Stack                                      Detail

MongoDB                                 It is A document-oriented database program based on NoSQL.

Express                                     It’s a robust Node.js web application framework that helps in creating powerful REST APIs.

React                                        A JavaScript library is 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.

 

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

 

Now, let’s learn in detail:

Step 1- Prerequisites

First of all, we need to build the MERN Stack Web Application for which we would install Node.js on our system. We will use the given command for doing so:

node -v

 

Step 2- Create React Application

Now, we will create a React app using the given command:

npx create-react-app react-mernstack-crud

Here, we will get inside the React project folder:

cd react-mernstack-crud

In order to start the React MERN stack project, we will run the command:

npm start

 

Step 3- Integrating React Bootstrap With React App

In this step, we will install the React Bootstrap front-end framework in our MERN stack app. This framework will allow us to use 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

Now, we have to import the Bootstrap into the src/App.js file and it will help us to create the UI components swiftly:

import "bootstrap/dist/css/bootstrap.css";

 

Step 4- Creating Simple React Components

In this step, we will learn how to create react components for managing data in the MERN stack CRUD app.

Afterward, we head over to the src folder. Make a folder and name it components. Within that directory, we need to create the following components:

  • create-student.component.js
  • edit-student.component.js
  • student-list.component.js

Then, we go to the 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>
    );
  }
}

We will go to the 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>
    );
  }
}

Now, we will go to the src/components/student-list.component.js and add the given code:

import React, { Component } from "react";
export default class StudentList extends Component {
  render() {
    return (
      <div>
        <p>React Student List Component!</p>
      </div>
    );
  }
}

 

Step 5- Implementing React Router

Here, we will learn how to simply implement react router in the React app.

We have to enter the command in the terminal and hit enter to install the React Router version 5. However, this tutorial is not compatible with react-router version 6:

react-router-dom@5.3.0

We have to create the service-worker file. So, we will create a service worker file in the src folder and add the given 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);
            });
    }
}

Further, we head over to the src/index.js file and tie the App component with the help of the <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, we have to include the menu in our React CRUD app. Then, we will add the given 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

 

Step 6- 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>);
  }
}

 

Step 7- Submit Forms data In React

Now, we will learn to submit the Forms data in React.js. We have already created the Student form and need to submit the student’s name, Email and Roll no to the database.

First of all, we will create the constructor inside the CreateStudent component class. Then, set the initial state of the CreateStudent component by setting this.state Object.

Then, we 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.

Further, we have to define the submit event which will allow us to create new student data when the user clicks on the ‘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>);
  }
}

 

Step 8- 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.

Now, we have to run the command to create the backend folder and get inside it:

mkdir backend && cd backend

Further, we need to create a separate package.json file for managing the backend of our React CRUD demo app example:

npm init

Next, we will install the given below Node dependencies for the 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 is a NoSQL document-oriented database for creating a robust web                                                           app.

CORS                                        It’s a node.js package that helps in enabling the Access-Control-Allow-                                                       Origin CORS header.

bodyParser                              This package extracts the entire body portion of an incoming request                                                           stream and exposes it o req.body.

Then, we will install the nodemon dependency to automate the server restarting process:

npm install nodemon --save-dev

 

Step 8- Define Mongoose Schema

In this step, we will create a MongoDB schema for interacting with MongoDB database. Then, we need to create a folder inside the backend folder to keep schema-related files and name them models ad then create a file Student.js inside it:

mkdir Models && cd Models && touch Student.js

Next, we include the given code in the 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 have declared a name, email and rollno fields along with their respective data types in student Schema.

 

Step 9- 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.

Afterward, we create a folder and name it routes. Here, we will keep all the routes-related files. Also, we will create the student.routes.js files inside this folder in this file, we will define REST APIs:

mkdir routes && cd routes && touch student.route.js

Then, go to the backend/routes/student.route.js file and add the given 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;

 

Step 10- Configure Server File

We have created almost 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.

Here, we have to run the command from the root of the backend folder to create the index.js file:

touch index.js

We paste the given 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 us to save the student data in the database:

mongod

Also, we open another terminal and run the given command to start the Nodemon server by stayi g in the backend folder:

cd backend && nodemon

 

Following will be our 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

 

Step 11- Using Axios With React To Make An HTTP request

In this step, we will see how to use the Axios library in React MERN Stack app to handle the HTTP request. We will run the below command in order to install Axios in React CRUD app:

npm install axios

Further, we will send the student’s data to the MongoDB server as an object using the Axios post HTTP method.

Then, we add the following code in the 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, we enter the student name, email and rollno and click on Create Student button. Then, our data will be saved in the MongoDB NoSQL database:

React MERN Stack CRUD App

 

Step 12- Show Data List With React Axios

here, we will see the student’s data list using React Axios and React Bootstrap. Then, we add the below code inside the src/components/student-list.component.js file:

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 the HTTP GET request using React Axios and Node/Express Js REST API. We are using the React-Bootstrap table to show the Students’ data on the front end.

In the next step, we are going to 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, we add the given 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>
        );
    }
}

 

Step 13- Edit, Update and Delete Data In React

Here, we have to 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 the MongoDB database using REST API built with Node and Express Js. Include the given 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>);
  }
}

 

Step 14- Make Axios Delete Request To Delete Data

Now, we will build the delete functionality in our React CRUD demo app. Then, we will go to the 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>
        );
    }
}

 

Step 15- Style CRUD App

In this step, we have to style the CRUD App by adding the customs CSS in the 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

So, we have reached the conclusion of this React MERN Stack CRUD app tutorial. We have learned to create a basic React CRUD app, set up React-Bootstrap and how we use its ready-made UI components in React app.

We have also learned to develop a Backend server using Node and Express js from scratch.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *