Logo


How To set Login Authentication to React Applications in react js


Let begin to do some code,the library which is needed is react-router-dom

1npm install react-router-dom

after installing package,we have to create a component dashboard which acts as a private page These will represent components that a user should not see until they have successfully logged into the application.

1import React from "react"
2
3export default class Dashboard extends React.Component {
4  render() {
5    return <h2>hloo dashboard </h2>;
6  }
7}

Now that you have some components, you need to import the components and create routes inside of App.js ,App.js file contains routes and conditional switching to login page with some props


1import "./styles.css";
2import React from "react";
3import Dashboard from "./Dasboard";
4import { BrowserRouter, Route, Routes } from "react-router-dom";
5import Login from "./Login";
6export default class App extends React.Component {
7  constructor(props) {
8    super(props);
9    this.state = {
10      token: false
11    };
12  }
13  handleCallback = (childData) =>{
14    console.log("ktytyt")
15    this.setState({token: childData})
16}
17setToken=(userToken)=>
18{
19  sessionStorage.setItem('token', JSON.stringify(userToken));
20}
21getToken=()=>
22{
23  const tokenString = sessionStorage.getItem('token');
24  const userToken = JSON.parse(tokenString);
25  return userToken?.token
26}
27  render() {
28    console.log("kokokokokok",this.state.token)
29    if (!this.state.token) {
30      console.log("kokoko");
31      return <Login token={this.state.token}  parentCallback = {this.handleCallback} />;
32    }
33    return (
34      <>
35        <div className="wrapper">
36          <h1>Application</h1>
37          <BrowserRouter>
38            <Routes>
39              <Route index to="/" element={<Dashboard />} />
40            </Routes>
41          </BrowserRouter>
42        </div>
43      </>
44    );
45  }
46}

A less intrusive option is to generate the login page regardless of the route. So we have to make a login page which get token from server.js file which is node file after getting token value on submitting ,we can execute to our private dashboard page,so login .js file is displayed below.


1import React from "react";
2import "./Login.css";
3import PropTypes from "prop-types";
4export default class Login extends React.Component {
5  constructor(props) {
6    super(props);
7    this.state = {
8      token: this.props.token,
9      Username: "",
10      password: ""
11    };
12  }
13  handleChange = (e) => {
14    this.setState({
15      Username: e.target.value
16    });
17  };
18  handleChangePass = (e) => {
19    this.setState({
20      password: e.target.value
21    });
22  };
23  loginUser = (credentials) => {
24    return fetch("http://localhost:8080/login", {
25      method: "POST",
26      headers: {
27        "Content-Type": "application/json"
28      },
29      body: JSON.stringify(credentials)
30    }).then((data) => data.json());
31  };
32  handleSubmit = async (e) => {
33    e.preventDefault();
34    const tokenval = await this.loginUser(
35      this.state.Username,
36      this.state.password
37    );
38
39    
40    console.log("token val", this.props.token);
41  
42   if(tokenval)
43   {
44     console.log("okokok")
45    this.props.parentCallback(true);
46    this.setState({
47      token: tokenval
48    });
49   }
50  };
51
52  render() {
53    console.log("render login");
54    return (
55      <>
56        <form onSubmit={(e) => this.handleSubmit(e)}>
57          <label>
58            <p>Username</p>
59            <input type="text" onChange={(e) => this.handleChange(e)} />
60          </label>
61          <label>
62            <p>Password</p>
63            <input type="password" onChange={(e) => this.handleChangePass(e)} />
64          </label>
65          <div>
66            <button type="submit">Submit</button>
67          </div>
68        </form>
69      </>
70    );
71  }
72}
73Login.propTypes = {
74  token: PropTypes.bool.isRequired
75};

In this step, you’ll create a local API to fetch a user token. You’ll build a mock API using Node.js that will return a user token. You’ll then call that API from your login page and render the component after you successfully retrieve the token. By the end of this step, you’ll have an application with a working login page and protected pages that will only be accessible after login

1const express = require('express');
2const cors = require('cors')
3const app = express();
4
5app.use(cors());
6
7app.use('/login', (req, res) => {
8  res.send({
9    token: 'test123'
10  });
11});
12
13app.listen(8080, () => console.log('API is running on http://localhost:8080/login'));

About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share