How to log-out user from app using ReactJS ?
The objective of this article is to how we can set up, log out a user, and retrieve data from local memory User Browser storage in the React app. During the sign-in session, we will save the user details to the browser’s local storage, and also during the time of logout, we will remove the user’s details from the local storage.
Prerequisites
Approach
To log-out user from app using ReactJS, we will be using LocalStorage API to store the user login data in the browser storage. When the logout button is clicked it triggers the function to remove the data stored and hence will log the user out clearing all of the user’s data.
LocalStorage is a web-based data storage device for a local user, which means that the data is stored in the browser sessions and the database does not have an expiration date. Through this local storage, we will perform a log-out for users of the Reactjs app.
Steps to create React App
Step 1: Create a React application using the following command.
npx create-react-app my-app
Step 2: After creating your project folder(i.e. my-app), move to it by using the following command.
cd my-app
Project structure
It will look like this.
Example: Implemented a basic login form that store informtion in local storage and remove the information then the user logs out ot the logout action is triggered.
Javascript
// Filename - App.js import { useState } from "react" ; import "./App.css" ; function App() { const [name, setName] = useState( "" ); const [email, setEmail] = useState( "" ); const [password, setPassword] = useState( "" ); const [isLoggedin, setIsLoggedin] = useState( false ); const login = (e) => { e.preventDefault(); console.log(name, email, password); const userData = { name, email, password, }; localStorage.setItem( "token-info" , JSON.stringify(userData) ); setIsLoggedin( true ); setName( "" ); setEmail( "" ); setPassword( "" ); }; const logout = () => { localStorage.removeItem( "token-info" ); setIsLoggedin( false ); }; return ( <> <div style={{ textAlign: "center" }}> <h1>This is React WebApp </h1> {!isLoggedin ? ( <> <form action= "" > <input type= "text" onChange={(e) => setName(e.target.value) } value={name} placeholder= "Name" /> <input type= "email" onChange={(e) => setEmail(e.target.value) } value={email} placeholder= "Email" /> <input type= "password" onChange={(e) => setPassword( e.target.value ) } value={password} placeholder= "Password" /> <button type= "submit" onClick={login} > GO </button> </form> </> ) : ( <> <h1>User is logged in </h1> <button onClickCapture={logout}> logout user </button> </> )} </div> </> ); } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project.
npm run start
Output: This output will be visible on http://localhost:3000/ on the browser window.
Contact Us