Skip to content

FocusScope

Keeps the keyboard inside a box, moves the focus in when it appears and gives it back when it goes.

import { FocusScope } from '@sypnia/ui/react'

On this page
  1. Focus kept inside
  2. When to use it
  3. For everyone
  4. Props

Focus kept inside

Code
import { useState } from 'react';
import { Button, FocusScope, Input } from '@sypnia/ui/react';

// Open it, then press Tab several times: focus stays inside. «Close» gives it back to the button.
export default function Trap() {
  const [open, setOpen] = useState(false);
  return open ? (
    <FocusScope contain autoFocus restoreFocus>
      <div className="sy-stack" style={{ '--gap': 'var(--s-3)', padding: 'var(--s-4)', border: '1px solid var(--line)', borderRadius: 'var(--r-3)', maxWidth: '22rem' } as React.CSSProperties}>
        <Input aria-label="Name" placeholder="Name" />
        <Input aria-label="Email" placeholder="Email" />
        <Button onClick={() => setOpen(false)}>Close</Button>
      </div>
    </FocusScope>
  ) : <Button onClick={() => setOpen(true)}>Open a box that keeps the focus</Button>;
}

When to use it

Use it when

  • A panel of your own that behaves like a dialog.

Do not use it when

  • Dialog, Drawer and Sheet: they already do it.

For everyone

  • Tab from the last control goes to the first, Shift+Tab the other way; focus returns to what opened it.

Props

FocusScopeTypeDefault
autoFocus boolean
contain boolean
restoreFocus boolean
  1. Focus kept inside
  2. When to use it
  3. For everyone
  4. Props

    Search pages, sections and terms