DEV Community

Cover image for Building a Login System using Redux
Daniel Onugha
Daniel Onugha

Posted on

Building a Login System using Redux

A login is a set of credentials used to authenticate a user. Most often, these consist of a username and password. However, a login may include other information, such as a PIN number, passcode, or passphrase. React Redux is the official React binding for Redux. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model. React Redux is conceptually simple.
When a login fails (i.e., the username and password combination does not match a user account), the user is disallowed access. Redux is an open-source JavaScript library for managing and centralizing application state. It is most commonly used with libraries such as React or Angular for building user interfaces.

Goal
In this article we are going to display how to create a Login System using Redux in React Applications.

Table of Content

  • Introduction
  • Creating our React App
  • Creating our Login Application
  • Login Value Inputs
  • Implementing Redux
  • Final Outputs
  • Conclusion

Installing and Setting up React
We will create a new React app with the command below:
npx create-react-app Login System

We have successfully installed our react application.

Creating our Components
We created the basic Components index.js and the App.js

The full index.js file

Image description

Below is the App.js after linking the all the folders and files to it

App.js

Creating our Component folder
Next Create a Component folder inside the src folder and name it Login.js. Open the file, copy the code below and paste it inside:


import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { login } from "../features/userSlice";
import "./Login.css";
const Login = () => {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const dispatch = useDispatch();
    const handleSubmit = (e) => {
      e.preventDefault();
      dispatch(
        login({
         name: name,
         email: email,
         password: password,
         loggedIn: true,
        })
      );
    };

    return (
        <div className="login">
          <form className="login_form" onSubmit={(e) => handleSubmit(e)}>
            <h1>Login Here đź“ť</h1>
            <input
             type="name" 
             placeholder="Name" 
             value={name} 
             onChange={(e) => setName(e.target.value)}
            />
            <input 
             type="email"
             placeholder="Email"
             value={email}
             onChange={(e) => setEmail(e.target.value)} 
            />
            <input
             type="password"
             placeholder="Password"
             value={password}
             onChange={(e) => setPassword(e.target.value)} 
            />
            <button type="submit" className="submit_btn">
              submit
            </button>
          </form>
        </div>
    );
};
export default Login
Enter fullscreen mode Exit fullscreen mode

Creating a Login button for our Form
Here we’re creating this using a type submit button using a special class “btn”, below are the block of codes used:

<button type="submit" className="submit_btn">
   submit
</button>
Enter fullscreen mode Exit fullscreen mode

We created a Login form in the code block above.
Styling the Login.js to beautify it, create a file under the Components folder named Login.css:

.login {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100vh;
    align-items: center;
    font-family: "Inter";
}
.login_form {
    display: flex;
    flex-direction: column;
}
.login_form>h1 {
    font-size: 35px;
    margin-bottom: 15px;
    padding-bottom: 10px;
    letter-spacing: -1px;
}
.login_form>input {
    min-width: 380px;
    padding: 20px 0;
    padding-left: 15px;
    margin-bottom: 10px;
    outline: none;
    border: 1px solid rgba(0, 0, 0, 0.24);
    font-family: "Inter";
    border-radius: 2px;
    font-size: 15px;
}
.submit_btn {
    padding: 17px 30px;
    margin-top: 10px;
    background: black;
    border: none;
    color: white;
    font-size: 14px;
    font-family: "Inter";
    border-radius: 3px;
}`
Enter fullscreen mode Exit fullscreen mode

Let’s also add some css to the App, so we start by creating a new file under the Component folder and we should name it App.css.

Image description
The code block above is basically adding styles to our App.

Creating a Logout File for our Form

Still the same way we created our Login.js file, create a file under the Components folder called Logout.js and it’s css (Logout.css):

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { logout, selectUser } from "../features/userSlice";
import "./Logout.css";
const Logout = () => {
  const user = useSelector(selectUser);
  const dispatch = useDispatch();
  const handleLogout = (e) => {
    e.preventDefault();
    dispatch(logout());
  };
    return (
        <div className="logout">
          <h1>
            Welcome <span className="user_name">{user.name}</span>
          </h1>{""}
          <button className="logout_button" onClick={(e) => handleLogout(e)}>
            Logout
          </button>
        </div>
    );
};
export default Logout;`
Enter fullscreen mode Exit fullscreen mode

Above is the full code block of our Logout.js file.

Creating the Logout button for our Form

Here we’re creating the Logout button, with the blocks of codes below;

<button className="logout_button" onClick={(e) => handleLogout(e)}>
  Logout
</button>
Enter fullscreen mode Exit fullscreen mode

You can add the following styles inside your Logout.css file;

Image description

Implementing Redux
The first step is to basically open a new folder, name it app, afterwards you create a file called store.js. After that we’re going to open another folder named features, you also create a file name userSlice.js.

Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application. To download redux toolkit, you have to look at the code block below :

# NPM
npm install @reduxjs/toolkit

# Yarn
yarn add @reduxjs/toolkit
Enter fullscreen mode Exit fullscreen mode

And also you have to install Redux itself:

# NPM
npm install react-redux

# Yarn
yarn add react-redux
Enter fullscreen mode Exit fullscreen mode

When you’re done installing it, the first thing is to import createSlice from Redux toolkit using the below block of code:

import { createSlice } from "@reduxjs/toolkit";
Enter fullscreen mode Exit fullscreen mode

Below is the userSlice.js file;

Image description

Image description

Above is the store.js, breaking it down we start by importing configureStore from Redux toolkit using the below code block:

import { configureStore } from "@reduxjs/toolkit";
Enter fullscreen mode Exit fullscreen mode

After inputting all the code and making sure our App is working.
This would be the result:

Image description

And, after clicking the submit button:

Image description

When you are done with the App, you click on Logout, it takes you back to a fresh form:

Image description

Conclusion
A Login form is used to enter authentication credentials to access a restricted page or form. The login form contains a field for the username and another for the password. When the login form is submitted its underlying code checks that the credentials are authentic, giving the user can access the restricted page.
In this article, we learnt about User Login using React and Redux.

Top comments (3)

Collapse
 
marialopez1 profile image
marialopez1

Nice

Collapse
 
danielonugha0 profile image
Daniel Onugha

Thanks ma'am

Collapse
 
angel_vera_9ed16ba3d96f62 profile image
Angel Vera

This is a great article!, adding a continuation with better navigation that gets rid of the success variable would be awesome!