import { Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { ModalFocus } from './modal-focus'; # ModalFocus `ModalFocus` traps the focus within the modal. This greatly improves the experience for screen readers and keyboard only users. ## Props The `ModalFocus` is built with [react-focus-lock](https://github.com/theKashey/react-focus-lock) and accepts all of the props from that library. ### Children Use the `children` prop to render the component to lock focus to ```jsx import React from 'react'; import { BorderColor, DISPLAY, FLEX_DIRECTION, } from '../../../helpers/constants/design-system'; import Box from '../../ui/box'; import { ModalFocus } from '../../component-library'; const [open, setOpen] = React.useState(false); ; { open && (

Modal focus children

Use the keyboard to try tabbing around you will notice that the focus is locked to the content within modal focus

); } ``` ### Initial Focus Ref Use the `initialFocusRef` to pass the `ref` of the element to receive focus initially ```jsx import React from 'react'; import { BorderColor, DISPLAY, FLEX_DIRECTION, } from '../../../helpers/constants/design-system'; import Box from '../../ui/box'; import { ModalFocus } from '../../component-library'; const [open, setOpen] = React.useState(false); const ref = React.useRef < HTMLButtonElement > null; ; { open && (

Initial focus is on the close button

); } ``` ### Final Focus Ref Use the `finalFocusRef` to pass the `ref` of the element to return focus to when `ModalFocus` unmounts ```jsx import React from 'react'; import { BorderColor, DISPLAY, FLEX_DIRECTION, } from '../../../helpers/constants/design-system'; import Box from '../../ui/box'; import { ModalFocus } from '../../component-library'; const [open, setOpen] = React.useState(false); const ref = React.useRef < HTMLInputElement > null; ; ; { open && (

Focus will be returned to the input once closed

); } ``` ### Restore Focus Use the `restoreFocus` to restore focus to the element that triggered the `ModalFocus` once it unmounts ```jsx import React from 'react'; import { BorderColor, DISPLAY, FLEX_DIRECTION, } from '../../../helpers/constants/design-system'; import Box from '../../ui/box'; import { ModalFocus } from '../../component-library'; const [open, setOpen] = React.useState(false); ; { open && (

Focus will be restored to the open button once closed

); } ``` ### Auto Focus Use the `autoFocus` to auto focus to the first focusable element within the `ModalFocus` once it mounts Defaults to `true` ```jsx import React from 'react'; import { BorderColor, DISPLAY, FLEX_DIRECTION, } from '../../../helpers/constants/design-system'; import Box from '../../ui/box'; import { ModalFocus } from '../../component-library'; const [open, setOpen] = React.useState(false); ; { open && (

auto focus set to false

); } ```