Ask Your Question
4

How can the Context API be utilized to implement guarded routes with React Router version 6?

asked 2023-07-20 08:45:51 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-20 09:06:02 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-07-20 08:45:51 +0000

Seen: 13 times

Last updated: Jul 20 '23