Start learning free

LESSON 111 OF 161 · FRONTEND: ACCESSIBLE, FAST, CORRECT

Where the Focus Goes

Practice

The focus is where the keyboard is: the control that Enter presses and that Tab moves on from. When something opens, like a cart panel, a keyboard visitor needs the focus inside it. When it closes, the focus must come back to where they were; otherwise it is lost, and they have to find their place again.

To focus an element you need the element itself. A ref holds it: useRef(null) makes the ref, the ref attribute fills ref.current once React has drawn the element, and ref.current.focus() moves the focus there:

const nameField = useRef(null);
// …
<input ref={nameField} />
<button type="button" onClick={() => nameField.current.focus()}>
  Edit name
</button>

An element that appears only after a state change, like the panel's Close button, doesn't exist yet while the click handler runs: focus it in a useEffect that runs when that state changes. A key pressed on any control inside the panel reaches the panel's onKeyDown, where event.key says which key it was.

Right now Enter opens the panel but the focus stays on Cart (3), and Escape does nothing. When you're done, the check must see:

> press Enter
  + aside "Cart"
  +   button: Close (focused)
> press Tab
  +   link: Checkout -> /checkout (focused)
> press Escape
  - aside "Cart"
  + button: Cart (3) (focused)
> click "Close"
  - aside "Cart"
  + button: Cart (3) (focused)

Your task: in src/App.jsx, make two refs, closeButton and openButton, for the Close and Cart buttons. In a useEffect on [open], focus the Close button when the panel is open. On the aside, call close() when Escape is pressed. And in close, focus the Cart button again.


Assignment
Follow the Coding Tutorial to move the focus into the cart panel when it opens, close it with Escape, and send the focus back to the Cart button when it closes.


Hint
A ref's element is in .current, and only once React has drawn it. That's why the Close button is focused in the effect, while the Cart button, which is always on the page, can be focused right inside close.


STEP 1 OF 9
    Ctrl + Enter to check