React – Frontend

Create the React project using the below command:

npx install create-react-app simple-login-project

In this project, we can require below components, so we can install using npm install command:

npm install component_name

Required components of this project

  • Axios
  • mdb-react-ui-kit
  • react-dom
  • react-router-dom

Once created the project with all required components and create the required directories and file, then the file structure looks like the below image.

File Structure

Step 1: Create the directory into src folder named as components in that folder we can create one react file and it named as SignUpPage for the building the signup frontend into the file.

Go to the src > components > SignUpPage and put the below code:

Javascript




import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom'; // Import useHistory hook
import {
    MDBContainer,
    MDBInput,
    MDBBtn,
} from 'mdb-react-ui-kit';
  
function SignupPage() {
    const [fullName, setFullName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [role, setRole] = useState('ROLE_CUSTOMER');
    const [mobile, setMobileNumber] = useState('');
    const [error, setError] = useState(''); // State to manage error messages
    const history = useNavigate(); // Get the history object for redirection
  
    const handleSignup = async () => {
        try {
            // Check for empty fields
            if (!fullName || !email || !password || !confirmPassword || !mobile) {
                setError('Please fill in all fields.');
                return;
            }
  
            if (password !== confirmPassword) {
                throw new Error("Passwords do not match");
            }
  
            const response = await axios.post('http://localhost:8081/auth/signup', {
                fullName,
                email,
                password,
                role,
                mobile
            });
            // Handle successful signup
            console.log(response.data);
            history('/dashboard');
        } catch (error) {
            // Handle signup error
            console.error('Signup failed:', error.response ? error.response.data : error.message);
            setError(error.response ? error.response.data : error.message);
        }
    };
  
    return (
        <div className="d-flex justify-content-center align-items-center vh-100">
            <div className="border rounded-lg p-4" style={{width: '600px', height: 'auto'}}>
                <MDBContainer className="p-3">
                    <h2 className="mb-4 text-center">Sign Up Page</h2>
                    {/* Render error message if exists */}
                    {error && <p className="text-danger">{error}</p>}
                    <MDBInput wrapperClass='mb-3' id='fullName' placeholder={"Full Name"} value={fullName} type='text'
                              onChange={(e) => setFullName(e.target.value)}/>
                    <MDBInput wrapperClass='mb-3' placeholder='Email Address' id='email' value={email} type='email'
                              onChange={(e) => setEmail(e.target.value)}/>
                    <MDBInput wrapperClass='mb-3' placeholder='Password' id='password' type='password' value={password}
                              onChange={(e) => setPassword(e.target.value)}/>
                    <MDBInput wrapperClass='mb-3' placeholder='Confirm Password' id='confirmPassword' type='password'
                              value={confirmPassword}
                              onChange={(e) => setConfirmPassword(e.target.value)}/>
  
  
                    <MDBInput wrapperClass='mb-2' placeholder='Mobile Number' id='mobileNumber' value={mobile}
                              type='text'
                              onChange={(e) => setMobileNumber(e.target.value)}/>
                    <label className="form-label mb-1">Role:</label>
                    <select className="form-select mb-4" value={role} onChange={(e) => setRole(e.target.value)}>
                        <option value="ROLE_CUSTOMER">User</option>
                        <option value="ROLE_ADMIN">Admin</option>
                    </select>
                    <button className="mb-4 d-block mx-auto fixed-action-btn btn-primary"
                            style={{height: '40px', width: '100%'}}
                            onClick={handleSignup}>Sign Up
                    </button>
  
                    <div className="text-center">
                        <p>Already Register? <a href="/">Login</a></p>
                    </div>
  
                </MDBContainer>
            </div>
        </div>
    );
}
  
export default SignupPage;


Step 2: In component folder, Create the another react file and it named as the LoginPage to building the login frontend into the page.

Go to the src > components > LoginPage and put the below code:

Javascript




import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import {
    MDBContainer,
    MDBInput,
    MDBBtn,
} from 'mdb-react-ui-kit';
  
function LoginPage() {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const history = useNavigate();
  
    const handleLogin = async () => {
        try {
            if (!username || !password) {
                setError('Please enter both username and password.');
                return;
            }
  
            const response = await axios.post('http://localhost:8081/auth/signin', { username, password });
            console.log('Login successful:', response.data);
            history('/dashboard');
        } catch (error) {
            console.error('Login failed:', error.response ? error.response.data : error.message);
            setError('Invalid username or password.');
        }
    };
  
    return (
        <div className="d-flex justify-content-center align-items-center vh-100">
            <div className="border rounded-lg p-4" style={{ width: '500px', height: 'auto' }}>
                <MDBContainer className="p-3">
                    <h2 className="mb-4 text-center">Login Page</h2>
                    <MDBInput wrapperClass='mb-4' placeholder='Email address' id='email' value={username} type='email' onChange={(e) => setUsername(e.target.value)} />
                    <MDBInput wrapperClass='mb-4' placeholder='Password' id='password' type='password' value={password} onChange={(e) => setPassword(e.target.value)} />
                    {error && <p className="text-danger">{error}</p>} {/* Render error message if exists */}
                    <button className="mb-4 d-block btn-primary" style={{ height:'50px',width: '100%' }} onClick={handleLogin}>Sign in</button>
                    <div className="text-center">
                        <p>Not a member? <a href="/signup" >Register</a></p>
                    </div>
                </MDBContainer>
            </div>
        </div>
    );
}
  
export default LoginPage;


Step 3: In component folder, create the another react file and it named as the Dashboard to building the simple dashboard frontend into the page.

Go to the src > components > Dashboard and put the below code:

Javascript




// WelcomeDashboard.js
import React from 'react';
import { useNavigate} from 'react-router-dom'; // Import useHistory hook
  
function WelcomeDashboard({ username }) {
    const history = useNavigate();
  
    const handleLogout = () => {
        // Perform logout actions here (e.g., clear session, remove authentication token)
        // After logout, redirect to the login page
        history('/');
    };
  
    return (
        <div className="d-flex justify-content-center align-items-center vh-100">
            <div className="border rounded-lg p-4" style={{width: '500px', height: '400px'}}>
                <h2 className="mb-4 text-center">Welcome to Dashboard</h2>
                <p className="mb-4 text-center">Hello, {username}!</p>
                <p className="text-center">You are logged in successfully.</p>
                <div className="text-center">
                    <button type="button" className="btn btn-primary mt-3" onClick={handleLogout}>Logout</button>
                </div>
            </div>
        </div>
    );
}
  
export default WelcomeDashboard;


Step 4: Open the app.js file and modified the code into the routing of the page into the login and signup pages of the project.

Note: No need to modify the remaining file of the project as per requirements of the project we are develop the frontend add into the app.js file.

Go to src > components > app and put the below code:

Javascript




import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import LoginPage from './components/LoginPage';
import SignupPage from './components/SignUpPage';
import Dashboard from "./components/Dashboard";
  
function App() {
  return (
      <div className="App">
      <Router>
  
            <Routes>
            <Route path="/" element={<LoginPage/>} />
            <Route path="/signup" element={ <SignupPage/>} />
                <Route path = "/dashboard" element={<Dashboard/>}/>
            </Routes>
  
      </Router>
      </div>
  );
}
  
export default App;


Step 5: Once the develop the frontend of the website we can run the application using below command once it runs successful it will run the port 3000.

npm start

Login Page:

Below is the login page.

Sign Up page:

Below is the sign-up page. We can now sign up by filling the necessary fields.

Simple Dashboard:

After logging in, we can see a simple Dashboard like below image.

Now we can develop the backend using the Spring Security. Once we can develop the spring security environment then endpoints of the spring boot project integrate with frontend using axios.

Spring Security Login Page with React

Spring Security is the most powerful and highly customizable authentication, and it is access control framework for Java enterprise applications and React is a popular JavaScript library for building for the user interfaces. Integrating Spring Security with the React frontend allows you to create the secure login pages and protect your application’s resources.

Similar Reads

Spring Security Login Page with React

The main concept involves to creating the React frontend that can be communicated with a Spring Boot backend secured with Spring Security. The react frontend will have a login page where users can input their credentials, and upon submission, these credentials will be sent to the backend for authentication. If the credentials are valid, the backend will generate a token (JWT) and send it back to the frontend. This token will be stored on the frontend side for subsequent requests to protected resources....

React – Frontend

Create the React project using the below command:...

Spring Security – Backend

...

Contact Us