-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathautofocus.tsx
39 lines (36 loc) · 1.14 KB
/
autofocus.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useRef, useState } from 'react'
import { FocusTrap } from '../focus-trap'
export const Autofocus = () => {
const [trapped, setTrapped] = useState(false)
const toggle = () => setTrapped((c) => !c)
const buttonRef = useRef<HTMLButtonElement | null>(null)
const getButtonNode = () => {
const node = buttonRef.current
if (!node) throw new Error('Button not found')
return node
}
return (
<div>
<button ref={buttonRef} onClick={toggle}>
{trapped ? 'End Trap' : 'Start Trap'}
</button>
{trapped && (
<FocusTrap disabled={!trapped} setReturnFocus={getButtonNode}>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '1rem',
paddingBlock: '1rem',
}}
>
<input type="text" placeholder="Regular input" />
{/* biome-ignore lint/a11y/noAutofocus: <explanation> */}
<input type="text" placeholder="Autofocused input" autoFocus />
<button onClick={() => setTrapped(false)}>End Trap</button>
</div>
</FocusTrap>
)}
</div>
)
}