Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.