Skip to content

Commit

Permalink
[docs] adds use case for TrapFocus (#33380)
Browse files Browse the repository at this point in the history
  • Loading branch information
EthanStandel committed Jul 17, 2022
1 parent 9e03901 commit 782f38f
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 0 deletions.
@@ -0,0 +1,33 @@
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import TrapFocus from '@mui/base/TrapFocus';

export default function BasicTrapFocus() {
const [open, setOpen] = React.useState(false);

return (
<Box
sx={{
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
}}
>
<TrapFocus open={open} disableRestoreFocus disableAutoFocus>
<Stack>
<Stack alignItems="center">
<button type="button" onClick={() => setOpen(!open)}>
{open ? 'Close' : 'Open'}
</button>
</Stack>
{open && (
<label>
First name: <input type="text" />
</label>
)}
</Stack>
</TrapFocus>
</Box>
);
}
@@ -0,0 +1,33 @@
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import TrapFocus from '@mui/base/TrapFocus';

export default function BasicTrapFocus() {
const [open, setOpen] = React.useState(false);

return (
<Box
sx={{
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
}}
>
<TrapFocus open={open} disableRestoreFocus disableAutoFocus>
<Stack>
<Stack alignItems="center">
<button type="button" onClick={() => setOpen(!open)}>
{open ? "Close" : "Open"}
</button>
</Stack>
{open && (
<label>
First name: <input type="text" />
</label>
)}
</Stack>
</TrapFocus>
</Box>
);
}
@@ -0,0 +1,14 @@
<TrapFocus open={open} disableRestoreFocus disableAutoFocus>
<Stack>
<Stack alignItems="center">
<button type="button" onClick={() => setOpen(!open)}>
{open ? "Close" : "Open"}
</button>
</Stack>
{open && (
<label>
First name: <input type="text" />
</label>
)}
</Stack>
</TrapFocus>
6 changes: 6 additions & 0 deletions docs/data/base/components/trap-focus/trap-focus.md
Expand Up @@ -50,6 +50,12 @@ This way, they are no longer part of the focus loop.

{{"demo": "PortalTrapFocus.js"}}

## Using a toggle inside the trap

The most common use case for the `TrapFocus` component is to maintain focus within a [`Modal`](/base/react-modal/) component which is entire separete from the element which would open the modal. However, there are use cases where you may want to have a toggle button for the `open` prop of the `TrapFocus` component which is stored inside that component.

{{"demo": "ContainedToggleTrappedFocus.js"}}

## Component size

- 📦 [2.0 kB gzipped](https://bundlephobia.com/package/@mui/base@latest)

0 comments on commit 782f38f

Please sign in to comment.