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)
.
UserMenu
functional component is the first component that uses ourAuthenticationContext
initialized inApp
. Withbutton
elements and theironClick
methods we can login or logout ouruser
by updatingAuthenticationContext
.SiteNavbar
component is the second component that usesAuthenticationContext
.
It displays ouruser
usinggetUser()
method from ourauthenticationService
and rendersUserMenu
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.
xxxxxxxxxx
1
// import React from 'react';
2
// import ReactDOM from 'react-dom';
3
4
const AuthenticationContext = React.createContext();
5
6
const UserMenu = () => {
7
const authenticationService = React.useContext(AuthenticationContext);
8
const handleLoginClick = () => authenticationService.loginUser('John');
9
const handleLogoutClick = () => authenticationService.logoutUser();
10
return (
11
<>
12
<button onClick={handleLoginClick}>Login John!</button>
13
<button onClick={handleLogoutClick}>Logout John!</button>
14
</>
15
);
16
};
17
18
const SiteNavbar = () => {
19
const authenticationService = React.useContext(AuthenticationContext);
20
return (
21
<div>
22
<UserMenu />
23
<br /><br />
24
<div>User: {authenticationService.getUser() ?? '<unknown>'}</div>
25
</div>
26
);
27
};
28
29
const App = () => {
30
const [user, setUser] = React.useState(null);
31
const authenticationService = {
32
getUser: () => user,
33
loginUser: (user) => {
34
//TODO: Replace setUser with AJAX request to server
35
setUser(user);
36
return true;
37
},
38
logoutUser: () => {
39
//TODO: Replace setUser with AJAX request to server
40
setUser(null);
41
return true;
42
}
43
// other methods ...
44
};
45
return (
46
<AuthenticationContext.Provider value={authenticationService}>
47
<SiteNavbar />
48
</AuthenticationContext.Provider>
49
);
50
};
51
52
const root = document.querySelector('#root');
53
ReactDOM.render(<App />, root);