//first rap app component with <AuthContextProvider> const { isLoggedIn } = useContext(AuthContext); let routes; if (isLoggedIn) { routes = ( <Routes> <Route exact path="/" element={<Users />} /> <Route exact path="/:userId/places" element={<UserPlaces />} /> <Route exact path="/places/new" element={<NewPlace />} /> <Route exact path="/places/:placeId" element={<UpdatePlace />} /> <Route path="*" element={<Navigate to="/" />} /> </Routes> ); } else { routes = ( <Routes> <Route exact path="/" element={<Users />} /> <Route exact path="/:userId/places" element={<UserPlaces />} /> <Route exact path="/auth" element={<Auth />} /> <Route path="*" element={<Navigate to="/auth" />} /> </Routes> ); } return ( <Router> <MainNavigation /> <main> {routes} </main> </Router > ); } export default App; //======================================================= auth-context file // import { createContext } from 'react'; // export const AuthContext = createContext({ // isLoggedIn: false, // login: () => {}, // logout: () => {} // }); import React, { createContext, useCallback, useState } from 'react'; export const AuthContext = createContext(); const AuthContextProvider = (props) => { const [isLoggedIn, setIsLoggedIn] = useState(false); const login = useCallback(() => { setIsLoggedIn(true); }, []); const logout = useCallback(() => { setIsLoggedIn(false); }, []); return ( <AuthContext.Provider value={{ isLoggedIn: isLoggedIn, login: login, logout: logout }}> {props.children} </AuthContext.Provider> ); } export default AuthContextProvider;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter