useFocusOnShow
useFocusOnShowは、要素が表示されたときに指定した要素にフォーカスをするカスタムフックです。
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>
)
こちらのコードを使用する場合は、
"use client"をファイルの上部に追加する必要があります。使い方
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,
})