useFocusOnShow
useFocusOnShow
is a custom hook that focuses on the target element when it is shown.
const [visible, setVisible] = useState(false)
const ref = useRef<HTMLElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
useFocusOnShow(ref, {
focusTarget: inputRef,
visible,
shouldFocus: true,
})
return (
<VStack alignItems="flex-start">
<Button onClick={() => setVisible((prev) => !prev)}>
{visible ? "Hide" : "Show"} Content
</Button>
<Fade ref={ref} open={visible} borderWidth={1} p="md" rounded="l2">
<Field.Root label="This input will be focused when shown">
<Input ref={inputRef} placeholder="Type something here" />
</Field.Root>
</Fade>
</VStack>
)
If you use this code, you need to add
"use client"
to the top of the file.Usage
import { useFocusOnShow } from "@yamada-ui/react"
import { useFocusOnShow } from "@/components/ui"
import { useFocusOnShow } from "@workspaces/ui"
const ref = useRef<HTMLElement>(null)
const focusTargetRef = useRef<HTMLElement>(null)
useFocusOnShow(ref, {
focusTarget: focusTargetRef,
visible: true,
shouldFocus: true,
})