React JS Login Page

Formal and informal pages can both be found on websites. A user simply must log in to access a formal page; an informal page is accessible to everyone. The user can restrict other users' access to the pages by using authentication. A React app will need to respond whenever a user attempts to visit a secret page without first logging in. The login information must be saved after successful authentication. In his article, we will talk more about the login pages in ReactJS and will create one too.

What is ReactJS?

ReactJS is a well-liked and commonly used Javascript library for making user interfaces. It is maintained by Facebook as well as a few other independent programmers along with businesses. It is mostly used for the development process of the front end and is well-established in the web development sector, especially for the creation of single-page user interfaces. Because of its rapid and straightforward interactive UI elements, it is well-liked among internet and mobile app developers.

React language is a more often used name for ReactJS. Due to its many practical advantages, ReactJS is favored by a large number of Fortune 500 firms. It helps programmers create websites that could also change data without reloading the page. It may be combined with other Javascript libraries like Node JS,  Angular JS, as well as Express JS.

Creating a login page in ReactJS

1. Declaration of the React State and isSubmitted

The following two React states will be declared:

  • errorMessages: Keep an object with the field name and the error message.
  • Submitted: A boolean value that represents whether or not the form was successfully submitted.
const [error_Message, setError_Message] = use_State({ });
const [is_Submitted, set_Is_Submitted] = use_State(false);
2. Returning a JSX code to generate an error message using the JS function

For showing the error message connected to the field name, the render_Error_Message function outputs JSX code.

const render_Error_Message = (name) =>
name === error_Messages.name && (<div class_Name="error">{error_Messages.message}</div> );

Become a React JS Certified professional by learning this HKR React JS Training !

React JS Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning
3. Creating a JSX code for the login page

To enable users to submit the form, we will add JSX code to an HTML form using the input type=" text" for the user name and password as well as input type="submit".

Below each form input element, we will additionally add error messages.

const render_Form = (
  <div class_Name="form">
   <form>
     <div class_Name="input-container">
     <label>Username </label>
     <input type="text" name="name" required />
     {render_Error_Message("name")}
 </div>
    <div className="input-container">
    <label>Pass </label>
   <input type="pass" name="passw" required />
   {render_Error_Message("passw")}
</div>
  <div class_Name="button-container">
  <input type="submit" />
</div>
  </form>
  </div>
);

reactjs login page

4. Adding functions for the Submission form

We need to develop a JS function for managing the submission of the form along with validations in order to add login functionality. The event.preventDefault() code avoids the default form submit action, which includes reloading the page when the function handle Submit() accesses the action object present in the form element.

const handle_Submit = (event) => {
event.prevent_Default();
};

Note: Avoid page reloading in this step

5. Validation of the form with details of the user

The first step in adding login features to a form is by specifying all the appropriate user information as JS constants. The subsequent actions are necessary to complete the functionality:

  • By matching usernames, locate expected user information.
  • If a match is not made, add an error message like "invalid username"; otherwise, validate the password; if validation fails, display the error code "invalid password".
  • If every validation is successful, use setIsSubmitted(true).
6. Success message post submission

React JS condition rendering will be added dependent on the value of the isSubmitted state.

  • Display the message "User is successfully logged in" if isSubmitted=true.
  • If isSubmitted=false, show the login form otherwise.
<div class_Name="login_form">
<div classN_ame="title">Sign In</div>
{isSubmitted ? <div>Login successful</div> : render_Form}
</div>

Want to know more about React Js,visit here React Js Tutorial !

Subscribe to our youtube channel to get new updates..!

Adding a Container

The root elements of various components present in a ReactJS application are commonly referred to as container components. They serve as a bridge between the logic that gives the user interface its interactive and dynamic features and the standard parts that make up the user interface.

The most common function of a container component is data acquisition. Data acquisition encompasses more than just getting information from an API endpoint; it also includes the reasoning behind a React component. The procedure is finished once the logic has been applied or data has been acquired in the component. It highlights the relevant component.

Let us see a React code below to add a container:

import React, { useState } from "react";
import Form from "Form";
import Button from "React Button";
import "Login file";
export default function Login1() {
   const [mail, setEmail] = useState("");
   const [pass, setPass] = useState("");
   function validateForm() {
    return mail.length > 0 && pass.length > 0;
  }
   function handleSubmit(event) {
   event.preventDefault();
  }
  return (
    <div className="Login">
     <Form onSubmit={handleSubmit}>
      <Form.Group size="lg" controlId="email">
       <Form.Label>Email</Form.Label>
        <Form.Control
         autoFocus
         type="mail"
        value={mail}
      onChange={(e) => setEmail(e.target.value)}
     />
     </Form.Group>
       <Form.Group size="lg" controlId="pass">
       <Form.Label>Pass</Form.Label>
       <Form.Control
       type="pass"
       value={pass}
       onChange={(e) => setPass(e.target.value)}
     />
      </Form.Group>
      <Button block size="lg" type="submit" disabled={!validateForm()}>
        Login1
       </Button>
       </Form>
    </div>
   );
   }

  • To save the data the user enters into the form, we use the 'useState' hook at the beginning of our component. The useState hook only offers a function to modify the variable's current value, which is what we want to keep in the state.
  • We next link the state to our two form fields by using the 'setEmail' and 'setPass' routines to record the user's input (e.target.value). After we modify the state, our component is re-rendered. The variables 'pass' and 'email' have been given new values.
  • The email and pass state variables' values are being shown using modified form controls. A React pattern called a Controlled Component will display the present value of the form as a variable and set a new one when the user enters data.
  • Our email field's autoFocus flag is set, so when the form runs, it will emphasize this field.
  • Additionally, we connect the 'submit' to the state using a validate method named validateForm. This only verifies that the variables really aren't empty, but it is simple to add further functionality.
  • We finally make a call to handleSubmit in our callback whenever the form is submitted.

Adding a route

The router in React is a common routing library in React. It enables users to switch between views of various React application components, modify the web URL, and maintain UI synchronization with the URL.

  <Route exact path="/login">
    <Login />
  </Route>

reactjs login

Prerequisites

  • A Node.js source code is required
  • With the unnecessary boilerplate removed, a React runtime environment has been set up using Create React App.
  • React will be used to retrieve data from APIs. Therefore, we need to learn API well.
  • Before beginning this project, we must also be well-versed in HTML, CSS, and Javascript.

React JS Training

Weekday / Weekend Batches

 Conclusion

A website can have both formal and informal pages. Considering that a formal page requires a user login but an informal page is open to anybody, authenticating is the most essential aspect of any website. It can be intimidating to combine security concerns with user experience, but if we focus on understanding and analyzing the components when they are needed, it can be a smooth process.

Other Articles:

Find our upcoming React JS Training Online Classes

  • Batch starts on 28th Sep 2023, Weekday batch

  • Batch starts on 2nd Oct 2023, Weekday batch

  • Batch starts on 6th Oct 2023, Fast Track batch

Global Promotional Image
 

Categories

Request for more information

Gayathri
Gayathri
Research Analyst
As a senior Technical Content Writer for HKR Trainings, Gayathri has a good comprehension of the present technical innovations, which incorporates perspectives like Business Intelligence and Analytics. She conveys advanced technical ideas precisely and vividly, as conceivable to the target group, guaranteeing that the content is available to clients. She writes qualitative content in the field of Data Warehousing & ETL, Big Data Analytics, and ERP Tools. Connect me on LinkedIn.

Add the following to a new file called src/containers/Login. js. To save the data the user enters into the form, we use the use State hook at the beginning of the component. The use_State hook only offers a function to modify the variable's current value, which is what we want to keep inside the state.

This can be done using 2 ways:

1.  Navigate component 

2. Using the useNavigate() hook

With the release of Router in React 6, The Navigate component took the place of the Redirect component and functions in a manner similar to that of the former, accepting the to prop to allow you to reroute to a page, you specify.

  • Run npm and create-react app MY APP for creating a React project.
  • Change the directory and type cd MY-APP to open your primary folder charting.
  • Use the fetch method to write your code in App. JS to get the data from an API.