,

Combining Full Stack Development with React, Spring Boot, and PostgreSQL

Posted by


In this tutorial, we will cover how to build a full stack application using React for the front end, Spring Boot for the back end, and PostgreSQL for the database.

Prerequisites:
Before we begin, make sure you have the following installed on your machine:

  • Node.js
  • npm
  • Java
  • Spring Boot
  • PostgreSQL

Step 1: Set up the Spring Boot back end

  1. Create a new Spring Boot project by going to https://start.spring.io/ and selecting the following options:

    • Project: Gradle Project
    • Language: Java
    • Spring Boot: 2.5.4
    • Group: com.example
    • Artifact: demo
    • Dependencies: Spring Web, Spring Data JPA, PostgreSQL Driver
  2. Extract the downloaded zip file and import the project into your IDE.

  3. Create a new package called ‘entity’ and create a new class called ‘User’. Add the following code to define the User entity:
package com.example.demo.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // getters and setters
}
  1. Create a new package called ‘repository’ and create a new interface called ‘UserRepository’. Add the following code to define the User repository:
package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}
  1. Create a new package called ‘controller’ and create a new class called ‘UserController’. Add the following code to define the User controller:
package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<User> getUsers() {
        return userRepository.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
}
  1. Run the Spring Boot application and test the createUser API using Postman. Make sure to have PostgreSQL running on your machine before running the application.

Step 2: Set up the React front end

  1. Create a new React project by running the following command:

    npx create-react-app frontend
  2. Navigate to the ‘frontend’ directory and install Axios for making HTTP requests by running the following command:

    npm install axios
  3. Create a new file called ‘api.js’ in the ‘src’ directory and add the following code to define the API endpoints:
import axios from 'axios';

const API_URL = 'http://localhost:8080/api/users';

export const getUsers = () => {
  return axios.get(API_URL)
    .then(response => response.data);
};

export const createUser = (user) => {
  return axios.post(API_URL, user)
    .then(response => response.data);
};
  1. Create a new file called ‘UserForm.js’ in the ‘src’ directory and add the following code to create a form to add new users:
import React, { useState } from 'react';
import { createUser } from './api';

const UserForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    await createUser({ name, email });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Name" value={name} onChange={e => setName(e.target.value)} />
      <input type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} />
      <button type="submit">Add User</button>
    </form>
  );
};

export default UserForm;
  1. Create a new file called ‘UserList.js’ in the ‘src’ directory and add the following code to display a list of users:
import React, { useState, useEffect } from 'react';
import { getUsers } from './api';

const UserList = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    getUsers().then(data => setUsers(data));
  }, []);

  return (
    <div>
      {users.map(user => (
        <div key={user.id}>
          <p>{user.name}</p>
          <p>{user.email}</p>
        </div>
      ))}
    </div>
  );
};

export default UserList;
  1. Update the ‘App.js’ file in the ‘src’ directory to include the UserForm and UserList components:
import React from 'react';
import UserForm from './UserForm';
import UserList from './UserList';

function App() {
  return (
    <div>
      <h1>User Management App</h1>
      <UserForm />
      <UserList />
    </div>
  );
}

export default App;
  1. Run the React application by running the following command:
    npm start

Step 3: Connect React front end to Spring Boot back end

  1. Update the ‘UserForm.js’ file in the ‘src’ directory to use Axios to make requests to the Spring Boot back end:
import React, { useState } from 'react';
import { createUser } from './api';

const UserForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    await createUser({ name, email });
    setName('');
    setEmail('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Name" value={name} onChange={e => setName(e.target.value)} />
      <input type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} />
      <button type="submit">Add User</button>
    </form>
  );
};

export default UserForm;
  1. Update the ‘api.js’ file in the ‘src’ directory to make requests to the Spring Boot back end:
import axios from 'axios';

const API_URL = 'http://localhost:8080/api/users';

export const getUsers = () => {
  return axios.get(API_URL)
    .then(response => response.data);
};

export const createUser = (user) => {
  return axios.post(API_URL, user)
    .then(response => response.data);
};
  1. Update the ‘UserController.java’ file in the ‘controller’ package in the Spring Boot back end to allow cross-origin requests from the React front end:
package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://localhost:3000")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<User> getUsers() {
        return userRepository.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
}
  1. Restart the Spring Boot application and the React application. You should now be able to add new users through the React front end and see them displayed in the user list.

Congratulations! You have successfully built a full stack application using React for the front end, Spring Boot for the back end, and PostgreSQL for the database. You can now customize and expand upon this application to meet your specific needs.