Login and Registration Application using Spring Boot and React

Overview

Welcome to our comprehensive guide on building a full-stack login and registration application using Spring Boot and React for the frontend. In this article, we’ll walk you through the entire process step-by-step, using simple and easy-to-understand language. By the end, you’ll have a fully functional application where users can register, log in, and interact with a secure backend.

Login and Registration Application using Spring Boot and React

If you haven’t already, check out our previous article on Building Robust Login and Registration REST APIs with Spring Boot, JPA, and MySQL to understand the backend setup. In this guide, we’ll focus on the React frontend and how to connect it to the Spring Boot backend.

What We’ll Build

  • Backend A Spring Boot application with REST APIs for user registration and login.
  • Frontend A React application with forms for registration and login.
  • 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.
  • Postman : For testing APIs.

Table of Contents:

  • Recap of the Spring Boot Backend
  • Setting Up the React Project
  • Create the Login and Registration Component
  • Set Up Routing in React
  • Connect React to Spring Boot
  • Enhance the Application

Step 1: Recap of the Spring Boot Backend

Before diving into the React frontend, let’s quickly recap the Spring Boot backend setup. If you haven’t set it up yet, follow our previous guide to create the following:

  • User Entity : A User class with fields like id, name, email, and password.
  • UserRepository : A Spring Data JPA repository for database operations.
  • UserService : A service to handle user registration and login logic.
  • UserController : REST endpoints for /addUser and /loginUser.

Step 2: Set Up a React project

for setup react project do the following things –

  • Make sure you have Node.js installed. Then, create a new React project using the following command:
  •    npx create-react-app my-app
  • Navigate to the project folder:
  •    cd my-app
  • Install react-router-dom for routing:
  •    npm install react-router-dom
  • Install Axios for API calls:
  •    npm install axios
  • Start the React app:
  •    npm run start

Step 3: Create the React Components

Folder Structure

Organize your React project like this:

src/
├── components/
│ ├── Register.js
│ ├── Login.js
├── App.js
├── index.js

1. Create Register component

Register.js In this component create one form for taking user information for registration


import React, { useState } from "react";
import axios from "axios";

function Register () {

    const [register, setRegister] = useState({
        name: "",
        email: "",
        password: "",
    });

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

    const handleSubmit = async (e) => {
        e.preventDefault();
        console.log(register);

        try {
            const response = await axios.post('http://localhost:8082/addUser', register);
            console.log(response.data);
            alert("User added successfully");
       } catch (error) {
            console.log(error);
       }
    };
    
    return (
       <div className="container">
          <form onSubmit={handleSubmit}>
            <h2>Register</h2>

            <label>Name:</label>
            <input type="text" name="name" placeholder="Enter your name" value={register.name} onChange={handleChange} />
            
<label>Email:</label> <input type="email" name="email" placeholder="Enter your email" value={register.email} onChange={handleChange} />
<label>Password:</label> <input type="password" name="password" placeholder="Enter your password" value={register.password} onChange={handleChange} />
<button type="submit">Register</button> </form> </div> ); } export default Register;

2. Create Login component

This component also contain one form for taking user email and password for login


import React, { useState } from "react";
import axios from "axios";

function Login() {
    
    const [password, setPasswordValue] = useState("");
    const [userId, setUserIdValue] = useState("");

    const setPassword = (e) => {
        setPasswordValue(e.target.value);
    };

    const setUserId = (e) => {
        setUserIdValue(e.target.value);
    };

    const handleSubmit = async (e) => {
        e.preventDefault(); // Prevent default form submission

        console.log("this is our data " + userId + "   " + password);

        const data = {
            userId: userId,
            password: password
        };

        try {
            const response = await axios.post("http://localhost:8082/loginUser", data);
            console.log("this is the response " + response.data);

            if (!response.data) {
                alert("Invalid User Id or Password");
            } else {
                alert("Login Successful");
            }

        } catch (error) {
            console.error(error);
        }
    };

    const redirectToRegister = () => {
        window.location.href = "/register";
    };

    return (
        <>
            <h1> This is login page </h1>
            <div className="container">
                <form onSubmit={handleSubmit}>

                    <label>User ID:</label>
                    <input type="email" placeholder="Enter your user id" 
                           value={userId} onChange={setUserId} />
                    <br /><br />

                    <label>Password:</label>
                    <input type="password" placeholder="Enter your password" 
                           value={password} onChange={setPassword} />
                    <br /><br />

                    <a onClick={redirectToRegister}>Don't have an account?</a>
                    <button type="submit">Login</button>
                    
                </form>
            </div>
        </>
    );
}

export default Login;

In the above Login and Register component we are calling spring boot api using axios this how you can call our backend api in react

Step 4: Set Up Routing in React

In App.js, set up routing to navigate between the login and registration pages:


import logo from './logo.svg';
import './App.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Login from './Login';
import Register from './Register';

function App() {
  return (
    <BrowserRouter>
        <Routes>
        <Route path="/" element={<Navigate to="/login" />} /> {/* Redirect to login */}
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        </Routes>
    </BrowserRouter>
  );
}

export default App;

Importing Dependencies –

  • BrowserRouter, Route, and Routes from react-router-dom for navigation.
  • Login and Register components to be displayed based on the route.

Setting Up Routing –

  • The <BrowserRouter> wraps the entire app to enable routing.
  • <Routes> contains multiple <Route> components
  • /login loads the Login component.
  • /register loads the Register component.

Step 5: Connect React to Spring Boot

Start the Spring Boot Application

  • Run your Spring Boot application on.
  • http://localhost:8080.

Start the React Application

  • Run your React application on.
  • http://localhost:3000.

Test the Application

  • Open your browser and go to http://localhost:3000/register .
  • Fill out the registration form and submit it. You should see a success message.
  • Navigate to http://localhost:3000/login and log in with the same credentials.

Step 6: Enhance the Application

Add Form Validation

Use libraries like Formik and Yup to add validation to your forms.

Store JWT Tokens

If you’re using JWT for authentication , store the token in localStorage or cookies after login.

Add Protected Routes

Use React Router to create protected routes that only logged-in users can access.

Conclusion

Congratulations! You’ve successfully built a full-stack login and registration web application using Spring Boot and React. Here’s what you’ve accomplished:

  • Created a secure backend with Spring Boot.
  • Built a user-friendly frontend with React.
  • Connected the frontend and backend using Axios.

This application is a great starting point for building more complex web applications. Feel free to expand it by adding features like password reset, email verification, or user profiles.

Youtube Video –

Github Repository –

https://github.com/amangupta7024/LoginRegisterFlow-SpringBoot-React

Explore our more articles

Create complete web application using spring boot and react

Welcome to our comprehensive guide on building a full-stack login and registration application using Spring Boot and React for the frontend. In this article, we’ll walk you through the entire process step-by-step, using simple and easy-to-understand language. By the end, you’ll have a fully functional application where users can register, log in, and interact with a secure backend.

How to connect react with spring boot

Connecting a React frontend with a Spring Boot backend is a common requirement for building full-stack web applications. In this section, we’ll explain how to connect React with Spring Boot in simple, easy-to-understand steps

1. Setting Up the React Project
2. Create the Login and Registration Component
3. Set Up Routing in React
4. Connect React to Spring Boot

1 thought on “Login and Registration Application using Spring Boot and React”

Leave a Comment