CRUD Operation using React and Spring Boot

CRUD Operation using React and Spring Boot

Overview

Looking to master CRUD operations using Spring Boot, React, and MySQL? You’re in the right place! In this complete full-stack guide, we’ll walk through how to create a student management system that performs Create, Read, Update, and Delete operations — from backend to frontend.

CRUD operation using react and spring boot

This article combines a Spring Boot backend with REST APIs, and a React.js frontend using Axios for API calls. If you’re a beginner or a developer aiming to build scalable, industry-standard applications, this CRUD tutorial is perfect for you.

What We’ll Build

  • Backend A Spring Boot application with REST APIs for CRUD Operations (Student Management System).
  • Frontend A React application with all the CRUD functionality like Add Student, Fetch Students, Update Student and Delete Student.
  • Integration Connecting the React frontend to the Spring Boot backend.

Tools and Technologies

  • Spring Boot : For building REST APIs.
  • React : For building the user interface..
  • MySQL : For storing user data.
  • Axios : For making HTTP requests from React to Spring Boot.

Table of Contents:

  • Recap of the Spring Boot Backend (CRUD rest apis)
  • Setting Up the React Project
  • Create the AddStudent and ViewStudents Components
  • Set Up Routing in React
  • Connect React to Spring Boot (Call Spring Boot APIs in React)
  • Conclusion

Step 1: Recap of the Spring Boot Backend

Before diving into the React frontend, let’s quickly recap the Spring Boot backend application where we implemented CRUD REST APIs. If you haven’t set it up yet, follow our Implement CRUD Operations using spring boot to create the following:

  • Student Entity : A Student class with fields like id, name, department, and age.
  • UserRepository : A Spring Data JPA repository for database operations.
  • UserService : A service to handle all student-related business logic..
  • UserController : REST endpoints for /addStudent, /getStudents, /deleteStudent/{id} and /updateStudent.

Step 2: Set Up a React project

Create a new React project:

 
npx create-react-app student-crud-app
cd student-crud-app
npm install axios react-bootstrap react-router-dom

Step 3: Create the AddStudent and ViewStudents Components

AddStudent.js

This component lets users add a student using a form:


import React, { useState } from "react";
import Form from "react-bootstrap/Form";
import axios from 'axios';

function AddStudent() {
  const [formData, setFormData] = useState({ id: "", name: "", dept: "", age: "" });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post("http://localhost:8082/addStudent", formData);
      alert("Student Added Successfully");
    } catch (error) {
      alert("Error while adding student");
    }
  };

  return (
    <>
      <h1> Add student </h1>
      <Form onSubmit={handleSubmit}>

        <Form.Group className="mb-3">
          <Form.Label>id</Form.Label>
          <Form.Control type="text" placeholder="id" name="id" onChange={handleChange} />
        </Form.Group>

        <br /><br />

        <Form.Group className="mb-3">
          <Form.Label>Name</Form.Label>
          <Form.Control type="text" placeholder="Enter your name" name="name" onChange={handleChange} />
        </Form.Group>

        <br /><br />

        <Form.Group className="mb-3">
          <Form.Label>Department</Form.Label>
          <Form.Control type="text" placeholder="Department" name="dept" onChange={handleChange} />
        </Form.Group>

        <br /><br />

        <Form.Group className="mb-3">
          <Form.Label>Age</Form.Label>
          <Form.Control type="text" placeholder="Age" name="age" onChange={handleChange} />
        </Form.Group>

        <Form.Group className="mb-3">
          <Form.Control type="submit" value="Submit" />
        </Form.Group>

      </Form>
    </>
  );
}

export default AddStudent;

ViewStudents.js

This component displays a list of students and supports update and delete operations.


import React, { useEffect, useState } from "react";
import axios from "axios";
import { Form } from "react-bootstrap";

function ViewStudents() {
  const [students, setStudents] = useState([]);
  const [selectedStudent, setSelectedStudent] = useState({
    id: "",
    name: "",
    dept: "",
    age: ""
  });
  const [isFormOpen, setFormOpen] = useState(false);

  useEffect(() => {
    fetchStudents();
  }, []);

  const fetchStudents = async () => {
    const baseURL = "http://localhost:8082/getStudents";
    try {
      const response = await axios.get(baseURL);
      setStudents(response.data);
    } catch (error) {
      console.error("Error fetching students:", error);
    }
  };

  const deleteStudent = async(id) => {
    const deleteURL = "http://localhost:8082/deleteStudent/" + id;
    try {
      await axios.delete(deleteURL);
      setStudents(students.filter((student) => student.id !== id));
    } catch (error) {
      console.error("Error deleting student:", error);
    }
  };

  const handleUpdate = (student) => {
    setSelectedStudent(student);
    setFormOpen(true);
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setSelectedStudent({ ...selectedStudent, [name]: value });
  };

  const updateStudent = async (e) => {
    e.preventDefault();
    const baseURL = "http://localhost:8082/updateStudent";
    try {
      await axios.post(baseURL, selectedStudent);
      setFormOpen(false);
      fetchStudents();
    } catch (error) {
      console.error("Error updating student:", error);
    }
  };

  return (
    <>
      <h1>This is your students</h1>

      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
            <th>Department</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {students.map((student) => (
            <tr key={student.id}>
              <td>{student.id}</td>
              <td>{student.name}</td>
              <td>{student.age}</td>
              <td>{student.dept}</td>
              <td>
                <button onClick={() => deleteStudent(student.id)}>Delete</button>
                <button onClick={() => handleUpdate(student)}>Update</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      <br />

      {isFormOpen && (
        <Form onSubmit={updateStudent}>

          <Form.Group className="mb-3">
            <Form.Label>ID</Form.Label>
            <Form.Control
              type="text"
              placeholder="ID"
              name="id"
              value={selectedStudent.id}
              onChange={handleChange}
              readOnly
            />
          </Form.Group>

          <br /><br />

          <Form.Group className="mb-3">
            <Form.Label>Name</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter your name"
              name="name"
              value={selectedStudent.name}
              onChange={handleChange}
            />
          </Form.Group>

          <br /><br />

          <Form.Group className="mb-3">
            <Form.Label>Department</Form.Label>
            <Form.Control
              type="text"
              placeholder="Department"
              name="dept"
              value={selectedStudent.dept}
              onChange={handleChange}
            />
          </Form.Group>

          <br /><br />

          <Form.Group className="mb-3">
            <Form.Label>Age</Form.Label>
            <Form.Control
              type="text"
              placeholder="Age"
              name="age"
              value={selectedStudent.age}
              onChange={handleChange}
            />
          </Form.Group>

          <Form.Group className="mb-3">
            <Form.Control type="submit" value="Submit" />
          </Form.Group>

        </Form>
      )}
    </>
  );
}

export default ViewStudents;

Step 4: Set Up Routing in React

In App.js, configure routing:


import { BrowserRouter, Routes, Route } from "react-router-dom";
import AddStudent from "./components/AddStudent";
import ViewStudents from "./components/ViewStudents";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="add-student" element={<AddStudent />} />
        <Route path="view-students" element={<ViewStudents />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Project Structure

src/
├── components/
│ ├── AddStudent.js
│ ├── ViewStudents.js
├── App.js
├── index.js

Step 5: Connect React to Spring Boot (Call Spring Boot APIs in React)

We’ve already done this using Axios inside our components. Just ensure:

  • Spring Boot app runs on http://localhost:8082
  • React runs on http://localhost:3000
  • CORS is enabled in your Spring Boot controller using:
    @CrossOrigin(origins = "http://localhost:3000")

Step 6: Conclusion

Congratulations! You now have a complete full-stack application with Spring Boot, React, and MySQL. This app demonstrates CRUD operations in action and is a great foundation to build more complex applications.

You can enhance this project by adding:

Youtube Video –

Github Repository –

https://github.com/amangupta7024/SpringBoot-React-CRUD-Operations

Explore our more articles

Leave a Comment