Languages
[Edit]
EN

React - simple login / logout service

3 points
Created by:
Dirask Community
5850

In this article, we would like to show you how to create a simple login/logout service in React.

In below example, we create an AuthenticationContext object which let us share a context between child components. Context lets us share some information across components without using props - all child components have access to the parent context.

Using AuthenticationContext.Provider we are able to share with all children authenticationService object. To access authenticationService object in any child it is necessary to call useContext(AuthenticationContext).

  • UserMenu functional component is the first component that uses our AuthenticationContext┬áinitialized in App.┬áWith button elements and their onClick methods we can login or logout our user by updating AuthenticationContext.
  • SiteNavbar component is the second component that uses AuthenticationContext.
    It displays our user using getUser() method from our authenticationService and renders UserMenu component.
  • User data is stored inside state in App component to force re-rendering for all components when user data are changed - user is logged in or logged out.
// ONLINE-RUNNER:browser;

//import React from 'react';
//import ReactDOM from 'react-dom';

const AuthenticationContext = React.createContext();

const UserMenu = () => {
    const authenticationService = React.useContext(AuthenticationContext);
  	const handleLoginClick = () => authenticationService.loginUser('john');
    const handleLogoutClick = () => authenticationService.logoutUser();
    return (
      <>
        <button onClick={handleLoginClick}>Login John!</button>
        <button onClick={handleLogoutClick}>Logout John!</button>
      </>
    );
};

const SiteNavbar = () => {
    const authenticationService = React.useContext(AuthenticationContext);
    return (
      <div>
        <span>{authenticationService.getUser()}</span>
        <UserMenu />
      </div>
    );
};

const App = () => {
  const [user, setUser] = React.useState(null);
  const authenticationService = {
      getUser: () => user,
      loginUser: (user) => {
          //TODO: Replace setUser with AJAX request to server
          setUser(user);
          return true;
      },
      logoutUser: () => {
          //TODO: Replace setUser with AJAX request to server
          setUser(null);
          return true;
      }
      // other methods ...
  };
  return (
    <AuthenticationContext.Provider value={authenticationService}>
      <SiteNavbar />
    </AuthenticationContext.Provider>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

ReactJS

React - login / logout service
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join