How to Create a Login Page In React?

React Login Form

In this post, we will learn about login form in react, how to create a login form using React JS with functions.

First install react and create react application

How To Install React JS and Setup Your React Application

Now Create Login.js component inside src

Import useState hook in login component

import React, {useState} from "react";

Declare submitted flag and error message with States

const [isSubmit, setIsSubmitted] = useState(false);
const [errormsg, setErrorMessages] = useState({});

Create Database object for login credentials

// Login credentials
  const database = [
    {
      username: "username",
      password: "password@123"
    }
  ];

Define error constant for form validation

 const errors = {
    username: "invalid username",
    password: "invalid password"
  };

Create Login Form

const loginForm = (
        <form onSubmit={handleSubmit}>
               <div className="form-group col-6 mt-5">
                    <label >User Name</label>
                    <input type="text" className="form-control" name="username" placeholder="Enter Username" />
                    {renderErrorMessage("username")}
                </div>

                <div className="form-group col-6 mt-3">
                    <label >Password</label>
                    <input type="password" className="form-control" name="password" placeholder="Enter Password" />
                    {renderErrorMessage("password")}
                </div>

                <div className="button-container mt-3">
                    <input type="submit" className="btn btn-primary"/>
                </div>

        </form>
    );

Define handleLoginForm() function for login form

const handleLoginForm = (event) => {
    //Prevent form 
    event.preventDefault();

    var { username, password } = document.forms[0];

    // Find user login info
    const userData = database.find((user) => user.username === username.value);

    // Compare user info
    if (userData) {
      if (userData.password !== password.value) {
        // Invalid password
        setErrorMessages({ name: "password", message: errors.password });
      } else {
        setIsSubmitted(true);
      }
    } else {
      // Username not found
      setErrorMessages({ name: "username", message: errors.username });
    }
  };

Use arrow function for error handling/validation

  const renderErrorMessage = (name) =>
    name === errormsg.name && (
      <div className="error">{errormsg.message}</div>
    );

Finally show result if login success

{isSubmit ? <div>Logged in successfully</div> : loginForm}

Import Login page inside app.js and access in App() function

import Login from './pages/Login.js';

function App() {
  return (
    <div className="App">
     <Login/>
    </div>
  );
}

Complete Login.js code

import React, {useState} from "react";

export default function Login(){

    const [isSubmit, setIsSubmitted] = useState(false);
    const [errormsg, setErrorMessages] = useState({});

// Login credentials
  const database = [
    {
      username: "username",
      password: "password@123"
    }
  ];

  const errors = {
    username: "invalid username",
    password: "invalid password"
  };

  const handleLoginForm = (event) => {
    //Prevent form reload
    event.preventDefault();

    var { username, password } = document.forms[0];

    // Find user login info
    const userData = database.find((user) => user.username === username.value);

    // Compare user info
    if (userData) {
      if (userData.password !== password.value) {
        // Invalid password
        setErrorMessages({ name: "password", message: errors.password });
      } else {
        setIsSubmitted(true);
      }
    } else {
      // Username not found
      setErrorMessages({ name: "username", message: errors.username });
    }
  };

    // JSX code for error message
    const renderErrorMessage = (name) =>
    name === errormsg.name && (
      <div className="error">{errormsg.message}</div>
    );

    const loginForm = (
        <form onSubmit={handleLoginForm}>
               <div className="form-group col-6 mt-5">
                    <label >User Name</label>
                    <input type="text" className="form-control" name="username" placeholder="Enter Username" />
                    {renderErrorMessage("username")}
                </div>

                <div className="form-group col-6 mt-3">
                    <label >Password</label>
                    <input type="password" className="form-control" name="password" placeholder="Enter Password" />
                    {renderErrorMessage("password")}
                </div>

                <div className="button-container mt-3">
                    <input type="submit" className="btn btn-primary"/>
                </div>

        </form>
    );
    return (
        <>
        <div className="container mt-5">
            <h2>Login </h2>
            {isSubmit ? <div>Logged in successfully</div> : loginForm}
            
        </div>
         

        </>
    )
}

Now run application using “npm start”

Conclusion

This post will helped us to create a login form with validation.

If you face any issue please comment your query.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *