Command Palette

Search for a command to run...

Hectal
Phase 13: Routing
React · Exercise 6 of 6 Previous
Intermediate

Protect a page and send the user back

The /account page should only be visible when logged in. Write a RequireAuth component that renders its children when user is set, and otherwise renders <Navigate to="/login" replace state={{ from: location.pathname }} />. Wrap the account page in it.

On the login page, the button #login logs in as Asha and then navigates to the page the user wanted (location.state?.from, or / if missing) with replace: true. The account page shows <h1 id="account">Account of Asha</h1>; the button #logout logs out.

The app starts on /account while logged out, so it must redirect to the login page (<h1 id="login-title">) at once.

What Check tests

  1. Logged out, /account redirects to the login page
  2. Logging in goes back to /account
  3. Logging out sends the user to the login page again
  4. Clicking My account while logged out also redirects
  5. Logging in from there returns to the account page

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.