DEV Community

Bello Toheeb
Bello Toheeb

Posted on

Creating an "Authentication" with "React Context API"

Introduction

Hi, My name is Bello, I am a Technical writer & Content writer (Visit Softwarify). Probably this is your first time reading an article I published. Trust me this article is very straightforward and informative article.

Despite there being many React and authentication tutorials out there, I feel like I have to showcase this.

I developed this React.js Authentication recently as an exam project for my second semester of study at AltSchool Africa, a one-year diploma online school focused on building software engineers in Africa.

Let’s begin on how to Authenticate users using Context API.

Time to Code

We’re going to be working with the files inside the src folder.

Our App will consist of 3 important routes. The Home, Login and User Dashboard. So we’re going to install react router to be able to use routing.

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Now type in the command above in your terminal to install React router to your project. Now that react installed, open your index .js file and import Browser Router from react-router-dom

import { BrowserRouter} from "react-router-dom";
Enter fullscreen mode Exit fullscreen mode

Then Enclose the Elements and components in the file with the BrowserRouter component like this;

import { BrowserRouter} from "react-router-dom"; 

 const root = ReactDOM.createRoot(document.getElementById('root')); 
 root.render( 
   <React.StrictMode> 
       <BrowserRouter> 
     <App /> 
     </BrowserRouter> 
   </React.StrictMode> 
 ); 
Enter fullscreen mode Exit fullscreen mode

This will allow our React router to perform optimally.

Next we open the App.js file and import Route and Routes. Then we create the required routes.

import React,{useState} from 'react'; 
 import LandingPage from './Pages/LandingPage/landingPage' 
 import ErrorPage from './Pages/404Page/pageError' 
 import  {AuthProvider} from "./Context/UserContext"; 
 import {Routes, Route, Navigate} from "react-router-dom"; 
 import Login from './Pages/Login/Login' 


 function App() { 
     const [fullName, setFullName] = useState(); 
     const [password, setPassword] = useState(""); 
   return ( 
     <AuthProvider> 
       <Routes> 
         <Route path="/" element={<LandingPage fullName={fullName}/>}/> 
           <Route path={"/login"} element={<Login fullName={fullName} setFullName={setFullName}password={password} setPassword={setPassword} />}/> 
         <Route path="*" element={<ErrorPage/>} /> 
       </Routes> 
     </AuthProvider> 
   ); 
 } 

 export default App;
Enter fullscreen mode Exit fullscreen mode

Next, we create a component folder inside our src folder and create a Nav.js file in it. The Nav.js file will serve as housing for our nav component which we will be using for navigation between the routes.

Inside the Nav.js file import NavLink and use it to establish a connection between the routes.

import React from 'react' 
 import './nav.css' 
 import {useAuth} from "../../Context/UserContext"; 
 import { Link } from "react-router-dom"; 

 export default function Nav() { 
     const {token, onLogout} = useAuth() 
     return ( 
         <div className="d-flex w-100 mx-auto p-3 flex-column" id={'nav-content'}> 
         <header className="mb-auto"> 
             <div> 
                 <h3 className="float-md-left mb-0" id={'brand'}>EliteAuth</h3> 
                 <nav id={'nav-nav'} className="nav nav-masthead align-items-center justify-content-center float-md-right"> 
                     <a className="nav-link active" aria-current="page" href="/">Home</a> 
                     {!token ? <Link to={'/login'}>Login</Link>  : <p onClick={()=> onLogout()}>Logout</p>} 
                 </nav> 
             </div> 
         </header> 
         </div> 
     ) 
 }
Enter fullscreen mode Exit fullscreen mode

Also, create a Layout component to host the routes.

Authentication

Create the Landingpage/Homepage. Next we make the routing in a way that when the Dashboard link is clicked, we are directed to the login page for the user to be authenticated before proceeding to the Dashboard.

So let’s start building our login page. We begin by creating a Login component and creating a basic login form in it like this;

import React, { useEffect } from "react"; 
 import { useAuth } from "../../Context/UserContext"; 
 import "./login.css"; 
 import { AiOutlineArrowLeft } from "react-icons/ai"; 
 import { useNavigate } from "react-router-dom"; 

 const AddUserForm = ({ fullName, setFullName, password, setPassword }) => { 
   const { token, onLogin } = useAuth(); 
   const navigate = useNavigate(); 

   const handleName = (e) => { 
     setFullName(e.target.value); 
     localStorage.setItem("fullName", fullName); 
   }; 
   const handlePassword = (e) => { 
     setPassword(e.target.value); 
     localStorage.setItem("password", password); 
   }; 

   useEffect(() => { 
     localStorage.setItem("fullName", fullName); 
     localStorage.setItem("password", password); 
   }, [token]); 
   return ( 
     <div className="login_page"> 
       <div> 
         <AiOutlineArrowLeft 
           onClick={() => navigate(-1)} 
           style={{ fontSize: "20px" }} 
         /> 
       </div> 
       <div className={"login-container"}> 
         <div className={"forms-container"}> 
           <h2>Sign up</h2> 
           <form className="login-form"> 
             <div className={"input-div"}> 
               <label className="form-label">Full name</label> 
               <input 
                 className="form-control input" 
                 value={fullName} 
                 onChange={(e) => handleName(e)} 
               /> 
             </div> 
             <div className={"input-div mt-3"}> 
               <label className="form-label">Password</label> 
               <input 
                 className="form-control input" 
                 value={password} 
                 onChange={(e) => handlePassword(e)} 
               /> 
             </div> 
             <button 
               disabled={!fullName} 
               type="submit" 
               onClick={(e) => onLogin(e)} 
             > 
               Submit 
             </button> 
             {!fullName && !password && ( 
               <p style={{ color: "red" }}> 
                 You have to fill form before you can submit 
               </p> 
             )} 
           </form> 
         </div> 
       </div> 
     </div> 
   ); 
 }; 
 export default AddUserForm;
Enter fullscreen mode Exit fullscreen mode

we import UseContext and UseState to the file.

Then we use the UseState to create the state of the page.

UseContext
We’re going to create the context for the authentication.

First we create a “Database” of some fake users.

export const fakeAuth = () => 
   new Promise((resolve) => { 
     setTimeout(() => resolve('2342f2f1d131rf12'), 250); 
   });
Enter fullscreen mode Exit fullscreen mode

Then we write the Context for the authentication.

import React, {createContext, useState,useEffect} from 'react'; 
 import {fakeAuth} from "./Auth" 
 import {useNavigate} from 'react-router-dom'; 

 const AuthContext = createContext({}); 

 export const AuthProvider = ({ children }) => { 
     const [token, setToken] = useState(localStorage.getItem('token') ); 
   const navigate = useNavigate(); 

     const handleLogin = async (e) => { 
         e.preventDefault() 
       const token = await fakeAuth(); 
       setToken(token); 
         localStorage.setItem('token', token); 
         navigate('/') 
     }; 
     const handleLogout = () => { 
       setToken(null); 
       localStorage.setItem('token', null); 
       localStorage.setItem('fullName', null); 
     }; 
   // useEffect(()=>{ 
   // 
   //   console.log(token) 
   // },[token]) 

     const value = { 
       token, 
       onLogin: handleLogin, 
       onLogout: handleLogout, 
     }; 
    
     return ( 
       <AuthContext.Provider value={value}> 
         {children} 
       </AuthContext.Provider> 
     ); 
   }; 

 export const useAuth = () => { 
     return React.useContext(AuthContext); 
 }; 
   export default AuthContext;
Enter fullscreen mode Exit fullscreen mode

Congratulations! We just created an authentication system with context API.

You can find the live demo of the project https://alt-school-project-main.vercel.app/

So that’s it on creating an Authentication system with React Context API.

Top comments (0)