How to create a login authentication in a React application

How to create a login authentication in a React application

Posted by Luke Beeno on June 17, 2022

How to create a login authentication in a React application

How to create a login authentication in a React application

Posted by Luke Beeno on June 17, 2022

You may need to set up a secure page in your React project. This page can only be accessed by user authentication. 

In this lession, you will be shown how to create a secure page by applying a token-based authentication technique. 

Step 1. Create the private page

import React, {Component} from 'react';
import {Navigate} from "react-router-dom";

class Dashboard extends Component {

    componentDidMount() {
        this.props.switchTab();
    }

    render() {
        const token = sessionStorage.getItem('token');

        if (token == null) {
            return <Navigate to={'/login'}/>
        }

        return (
            <h2>Dashboard</h2>
        );
    }
}
export default Dashboard;

You will be able to view the Dashboard component once the auth token is stored in session storage and the nav tab will switch from login to logout using the prop method switchTab. If the token does not exist users will be redirected to the login page.

Step 2. Create the login page

Edit the Login component to look like this:

import React, {Component} from "react";
import {Navigate} from "react-router-dom";

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userName:"",
            password:"",
            goToDashboardPge:false,
        };
        this.handleSubmit = this.handleSubmit.bind(this)
    }

    handleSubmit (e) {
        e.preventDefault();

        if(this.state.password !== "please1" && this.state.userName !== "scott") {
            alert("credentials are incorrect");
        }else{
            this.setState({goToDashboardPge: true});
            sessionStorage.setItem('token', "[qK5fy5d#KMA*sAf");
        }
    }

    render() {
        if(this.state.goToDashboardPge) {
            return <Navigate to={{pathname:'/dashboard'}}/>
        }

        return (
            <div className="container">
                <div className="col-6 mx-auto">
                    <h3 className="mb-4">Login</h3>
                    <form onSubmit={this.handleSubmit}>
                        <div className="mb-3">
                            <label>Username</label>
                            <input type="text" className="form-control" onChange={e => this.setState({userName:e.target.value})} required/>
                        </div>
                        <div className="mb-3">
                            <label>Password</label>
                            <input type="password" className="form-control" onChange={e => this.setState({password: e.target.value})} required/>
                        </div>
                        <div>
                            <button type="submit" className="btn btn-primary">Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}
export default Login;

The Login component collects the users username and password. If the users credentials are correct, a token value will be stored in session storage and the state goToDashboardPge value is set from false to true.

In this example static data is used to test the logic. However, in reality you would use axios to query a database via api in order to check users credentials. In any case I hope you get the idea of the login technique.

Step 3. Amend the base component accordingly

Here is an example of the base component:

import React, { Component } from "react";
import {BrowserRouter as Router, Route, Link, Routes} from "react-router-dom";
import './App.css';
import "bootstrap/dist/css/bootstrap.min.css";
import Dashboard from "./dashboard/Dashboard";
import Login from "./Authenticate/Login";
import Home from "./home/Home";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            token:null,
        };
    }

    switchTab = () => {
        this.setState({ token: sessionStorage.getItem('token')});
    }

    render() {

        return (
            <Router>
                <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
                    <div className="container">
                        <Link to="/" className="navbar-brand">Home</Link> {/*Clickable links related to the Router*/}
                        <div className="collpase navbar-collapse">
                            <ul className="navbar-nav ms-auto">
                                {(this.state.token != null)?<li className="navbar-item">
                                    <Link to="#" className="nav-link">Logout</Link>
                                    </li>:<li className="navbar-item">
                                    <Link to="/login" className="nav-link">Login</Link>
                                </li>}
                            </ul>
                        </div>
                    </div>
                </nav>
                <div className="container">
                    <br/>
                    <Routes>
                        <Route path="/" exact element={<Home/>}/>
                        <Route path="/login" element={<Login/>}/>
                        <Route path="/dashboard" element={<Dashboard  switchTab={this.switchTab}/>}/>
                    </Routes>
                </div>
            </Router>
        );
    }
}

export default App;

Download project here

If you download the project above, please run npm install before launching the project.

Hopefully this will give you ideas to help build your own React app login system.

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question