EN
React - simple login / logout service
3
points
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).
UserMenufunctional component is the first component that uses ourAuthenticationContextinitialized inApp. Withbuttonelements and theironClickmethods we can login or logout ouruserby updatingAuthenticationContext.SiteNavbarcomponent is the second component that usesAuthenticationContext.
It displays ouruserusinggetUser()method from ourauthenticationServiceand rendersUserMenucomponent.- User data is stored inside state in
Appcomponent 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>
<UserMenu />
<br /><br />
<div>User: {authenticationService.getUser() ?? '<unknown>'}</div>
</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);