Utilizing React and Spring Boot for Simple CRUD Application Development

In recent years, combining robust backend technologies with dynamic frontend libraries has become a widespread practice in web development. One of the most popular combinations is React for the frontend and Spring Boot for the backend. This article aims to guide you through building a simple CRUD (Create, Read, Update, Delete) application using this powerful pair.

Introduction

  • React is a widely used JavaScript library for building user interfaces, especially for single-page applications. It’s known for its virtual DOM feature that optimizes rendering and improves app performance.
  • Spring Boot is an extension of the Spring framework which simplifies the setup of new Spring applications. It’s a powerful tool to create stand-alone, production-grade Spring-based applications with minimum configuration.

Prerequisites

Before we begin, make sure to have the following installed on your system:

  • Node.js and npm: Needed to run the React application.
  • Java Development Kit (JDK): Required to develop and run Spring Boot applications.
  • Integrated Development Environment (IDE): Such as IntelliJ IDEA or Visual Studio Code.
  • Spring Boot Initializr: A tool to bootstrap your Spring Boot project.

Step-by-Step Guide

Step 1: Set Up Spring Boot Backend

1.1 Generate a New Spring Boot Project

Use the Spring Boot Initializr to generate a new project with Web, JPA, and H2 dependencies.

1.2 Create Entity Class

Create a Java class representing the entity (e.g., Employee.java) in your application, with attributes such as id, name, and designation.

@Entity
public class Employee {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private String name;
   private String designation;

   // getters and setters
}
1.3 Create Repository Interface

Create a repository interface extending JpaRepository to perform CRUD operations on the entity.

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
1.4 Create a REST Controller

Implement a REST controller with mappings for CRUD operations.

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

   @Autowired
   private EmployeeRepository employeeRepository;

   @GetMapping("/")
   public List<Employee> getEmployees() {
       return employeeRepository.findAll();
   }

   @PostMapping("/")
   public Employee createEmployee(@RequestBody Employee employee) {
       return employeeRepository.save(employee);
   }

   @PutMapping("/{id}")
   public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee employeeDetails) {
       Employee employee = employeeRepository.findById(id)
               .orElseThrow(() -> new ResourceNotFoundException("Employee not found"));

       employee.setName(employeeDetails.getName());
       employee.setDesignation(employeeDetails.getDesignation());

       return employeeRepository.save(employee);
   }

   @DeleteMapping("/{id}")
   public ResponseEntity<?> deleteEmployee(@PathVariable Long id) {
       employeeRepository.deleteById(id);
       return ResponseEntity.ok().build();
   }
}

Step 2: Create React Frontend

2.1 Create a New React Project

Use Create React App to generate a new React project.

npx create-react-app react-springboot-crud
2.2 Create Components

Develop React components for listing, creating, updating, and deleting entities.

  • EmployeeList.js: To list all the employees.
  • EmployeeForm.js: To handle the creation and updating of employees.
  • Employee.js: A component to display individual employee details.
2.3 Implement API Calls

Use libraries like axios to implement API calls to the backend services.

import axios from 'axios';

const EMPLOYEE_API_BASE_URL = "http://localhost:8080/api/employees";

class ApiService {

    fetchEmployees() {
        return axios.get(EMPLOYEE_API_BASE_URL);
    }

    fetchEmployeeById(employeeId) {
        return axios.get(EMPLOYEE_API_BASE_URL + '/' + employeeId);
    }

    deleteEmployee(employeeId) {
        return axios.delete(EMPLOYEE_API_BASE_URL + '/' + employeeId);
    }

    addEmployee(employee) {
        return axios.post(""+EMPLOYEE_API_BASE_URL, employee);
    }

    editEmployee(employee) {
        return axios.put(EMPLOYEE_API_BASE_URL + '/' + employee.id, employee);
    }

}

export default new ApiService();

Step 3: Integrate React with Spring Boot

3.1 Enable CORS in Spring Boot

To allow the React app to communicate with the Spring Boot backend, enable CORS in the Spring Boot application.

@Configuration
public class WebConfig implements WebMvcConfigurer {

   @Override
   public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**")
               .allowedMethods("GET", "POST", "PUT", "DELETE")
               .allowedHeaders("*")
               .allowedOrigins("http://localhost:3000");
   }
}
3.2 Connect React Components with API Services

In the React components, make API calls to the Spring Boot backend and update the component state accordingly.

// In EmployeeList.js
componentDidMount() {
    ApiService.fetchEmployees()
        .then((res) => {
            this.setState({employees: res.data})
        });
}

// In EmployeeForm.js
handleSubmit(event) {
    event.preventDefault();

    // Logic to make API calls to add or update employee
}

Conclusion

By following this guide, you should now have a simple CRUD application with a React frontend and a Spring Boot backend. This combination leverages the strengths of both technologies, offering a streamlined development process and a dynamic, user-friendly end product. Remember to continually explore and implement new features and optimizations as you become more familiar with both React and Spring Boot.

Leave a Comment

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

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top