Start learning free

LESSON 106 OF 161 · FRONTEND: REACT ROUTES AND SHARED STATE

Pages for Signed-in Visitors in JavaScript

Practice

Some pages only make sense for a visitor who has logged in. /account shows Logged in as …, and with nobody logged in it crashes. A guard is a component around such a page: it draws the page when someone is logged in, and otherwise sends the visitor to /login.

React Router's Navigate component moves the visitor as soon as it is drawn, like a click on a link. It is handy for an old address that has moved:

<Route path="/shop" element={<Navigate to="/" replace />} />

replace puts the new address in place of the current one in the history, so Back doesn't lead to the old address again. Navigate can also carry state, an object the next page reads from useLocation().state. The given LoginPage reads state.from and goes there after Log in. useLocation().pathname is the address the visitor asked for.

The check opens the cart, clicks Account with nobody logged in, logs in and presses Back:

> open /cart
> click "Account"
    +   section "Log in"
> the address bar
  /login
> type "ana@example.com" into "Email"
> click "Log in"
    +     heading 2: Your account
    +     text: Logged in as ana@example.com
> the address bar
  /account
> press the browser's Back button
    +   section "Cart"

Your task: in src/RequireUser.jsx, read user from useUser() and the location from useLocation(). When user is null, return a Navigate to /login with replace and the asked-for path in state.


Assignment
Follow the Coding Tutorial to write the guard RequireUser, which App.jsx already puts around AccountPage.


Hint
useUser() gives { user, login, logout }, and user is null until someone logs in. In JSX, state takes an object, so it needs two pairs of braces: state={{ from: … }}.


STEP 1 OF 4
    Ctrl + Enter to check

    Route Protected in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free