The Context API can be utilized to implement guarded routes with React Router version 6 by creating a context to store the authenticated state and passing it down to the routes that require authentication.
Here's an example:
1) First, create a context for the authenticated state.
const AuthContext = React.createContext(false);
2) Wrap the routes that require authentication with the AuthProvider component, which will provide the authenticated state to the child components.
function App() {
return (
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/login" element={<Login />} />
<Route path="/logout" element={<Logout />} />
</Routes>
</AuthProvider>
</BrowserRouter>
);
}
3) In the AuthProvider component, initialize the authenticated state using local storage or another method.
function AuthProvider(props) {
const [authenticated, setAuthenticated] = useState(
localStorage.getItem("authenticated") || false
);
const login = () => {
localStorage.setItem("authenticated", true);
setAuthenticated(true);
};
const logout = () => {
localStorage.removeItem("authenticated");
setAuthenticated(false);
};
return (
<AuthContext.Provider value={{ authenticated, login, logout }}>
{props.children}
</AuthContext.Provider>
);
}
4) In the components that require authentication, use the useContext hook to access the authenticated state.
function Dashboard() {
const { authenticated } = useContext(AuthContext);
if (!authenticated) {
return <Navigate to="/login" />;
}
return (
<>
<h1>Dashboard</h1>
<button onClick={logout}>Logout</button>
</>
);
}
In this example, if the user is not authenticated, they will be directed to the login page using the Navigate component from React Router. If they are authenticated, the Dashboard component will be rendered and the user can logout using the logout function passed down from the AuthContext.Provider.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-20 08:45:51 +0000
Seen: 13 times
Last updated: Jul 20 '23
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?
How can popen() be used to direct streaming data to TAR?
How does iOS retrieve information from a BLE device?
How can Django Admin accommodate a variety of formats and locales for its input fields?