We can help you develop your capabilities until you achieve your dream

Digital marketing

How to Build a React Login Page: Complete Guide for Beginners

Create a login page for our application at this stage. Installing React Router and designing components to represent a comprehensive application are the first steps. The login page will then be rendered on any route, allowing our users to log in without being transferred to a new page.

To begin, use npm to install react router. There are two versions available: a browser version and a native version that can be used with React Native. Installing the web version is preferred.

The package will be installed, and we will be notified when it is finished.

Then, as private pages, add two components called Dashboard and Preferences. These are components that should not be shown to users until they have successfully signed into the application.

Then, in a text editor, open Dashboard.js. Nano will be used in this tutorial.

Follow the same procedure for Preferences.

After creating some components, we’ll need to import them and define routes in App.js.

Then, from react-router-dom, import BrowserRouter, Switch, and Route.

so that our component does not sit directly on the browser’s edge. We’ll need to update the CSS to accomplish this.

Open App.css

nano src/components/App/App.css

Replace the contents with a.wrapper class with a 20px padding.

.wrapper {

    padding: 20px;

}

The file should be saved and closed. The browser will reload, and we’ll see the basic components.

Login_Page_in_ReactJS_2

Login_Page_in_ReactJS_3.

Now, it’s up to us to add some styling which is completely optional.

Check each of the routes, and we will find our dashboard pages.

Step 2 — Creating a Token API

We’ll construct a local API to get a user token in this stage. We’ll use Node.js to create a mock API that returns a use. \r token. After successfully retrieving the token, we’ll use that API from our login page and render the component. By the end of this stage, we’ll have a working login page as well as protected sites that can only be accessed after logging.

We’ll need a server that will operate as a backend and return the token. Using Node.js and the Express web framework, we can easily establish a server.

To begin, download and install express. Because the server isn’t required for the final build, install it as a devDependency.

We’ll also have to set up cors. This library will allow all routes to share resources across origins.

npm install –save-dev express cors

We’ll get a success message when the installation is finished.

Then, at the root of our application, create a new file named server.js. Because we don’t want this file to be part of the final build, don’t put it in the /src directory.

Import express, then call express() to create a new app and save the output to a variable called app.

const express = require(‘express’);

const app = express();

Add cors as a middleware after we’ve finished building the app. Import cors first, then execute the use method on app to add it to the app.

const express = require(‘express’);

const cors = require(‘cors’);

const app = express();

app.use(cors());

Then, using app.use, listen to a certain route. The first argument is the path that the application will listen to, and the second specifies a callback function that will be executed when the path is served. The callback takes two arguments: a req argument that has the request data, and a res argument that holds the result.

A handler for the /login path should be added. With a JavaScript object holding a token, call res.send.

const express = require(‘express’);

const cors = require(‘cors’)

const app = express();

app.use(cors());

app.use(‘/login’, (req, res) => {

  res.send({

    token: ‘test123’

  });

});

Last but not least, start the server on port using app.listen.

const express = require(‘express’);

const cors = require(‘cors’)

const app = express();

app.use(cors());

app.use(‘/login’, (req, res) => {

  res.send({

    token: ‘test123’

  });

});

app.listen(8080, () => console.log(‘API is running on http://localhost:8080/login’));

The file should be saved and closed. Start the server in a new terminal window or tab.

Login_Page_in_ReactJS_4

We’ll get a response that says the server is setting up:

Output:

API is running on http://localhost:8080/login

Want a Top Software Development Job? Start Here!

Full Stack Developer – MERN StackExplore Program

Want a Top Software Development Job? Start Here!

Now that our API server is up and running, we must make a request from our login page. Login.js is now open.

nano src/components/Login/Login.js

We gave the Login component a new prop named setToken in the previous step. Destructure the props object to extract the setToken prop and add the PropType from the new prop.

import React from ‘react’;

import PropTypes from ‘prop-types’;

import ‘./Login.css’;

export default function Login({ setToken }) {

  return(

    

      

      

    

  )

}

Login.propTypes = {

  setToken: PropTypes.func.isRequired

}

Make a local state to save the Username and Password. Make the unregulated components, so we don’t have to explicitly specify data. 

import React, { useState } from ‘react’;

import PropTypes from ‘prop-types’;

import ‘./Login.css’;

export default function Login({ setToken }) {

  const [username, setUserName] = useState();

  const [password, setPassword] = useState();

  return(

    

      

      

        

          

Username

           setUserName(e.target.value)}/>

        

        

          

Password

           setPassword(e.target.value)}/>

        

        

          

        

      

    

  )

}

Login.propTypes = {

  setToken: PropTypes.func.isRequired

};

Create a function that performs a POST request to the server. These would be placed in a separate directory in a large application. In this case, we’ll add the service to the component directly. 

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program

Learn From The Best Mentors in the Industry!

Create the loginUser async function. The function will take credentials as an input and then use the POST option to call the retrieve method:

import React, { useState } from ‘react’;

import PropTypes from ‘prop-types’;

import ‘./Login.css’;

async function loginUser(credentials) {

 return fetch(‘http://localhost:8080/login’, {

   method: ‘POST’,

   headers: {

     ‘Content-Type’: ‘application/json’

   },

   body: JSON.stringify(credentials)

 })

   .then(data => data.json())

}

export default function Login({ setToken }) {

Finally, construct a handleSubmit form submission handler that will provide the username and password to loginUser. With a successful outcome, call setToken. 

Use the onSubmit event handler on the form to call handleSubmit.

import React, { useState } from ‘react’;

import PropTypes from ‘prop-types’;

import ‘./Login.css’;

async function loginUser(credentials) {

 return fetch(‘http://localhost:8080/login’, {

   method: ‘POST’,

   headers: {

     ‘Content-Type’: ‘application/json’

   },

   body: JSON.stringify(credentials)

 })

   .then(data => data.json())

}

export default function Login({ setToken }) {

  const [username, setUserName] = useState();

  const [password, setPassword] = useState();

  const handleSubmit = async e => {

    e.preventDefault();

    const token = await loginUser({

      username,

      password

    });

    setToken(token);

  }

  return(

    

      

      

        

          

Username

           setUserName(e.target.value)} />

        

        

          

Password

           setPassword(e.target.value)} />

   


Source link

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

زر الذهاب إلى الأعلى

Please turn off the ad blocker, as ads are the only source of our continuity

برجاء دعمنا عن طريق تعطيل إضافة Adblock