🔰
TypeScriptでuseImperativeHandleを使う
useImperativeHandleのドキュメントを読んでいて、TypeScriptでどう書くか迷ったのでメモです。
結論
React19ではRefObjectに渡す型をPickしてあげると良さそう。
type FormProps = {
ref: RefObject<Pick<HTMLInputElement, "focus"> | null>;
};
export const Form = ({ ref }: FormProps) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(
ref,
() => ({
focus: () => {
if (inputRef.current) {
inputRef.current.focus();
}
},
}),
[],
);
return <input ref={inputRef} className="border" />;
};
export default function Home() {
const ref = useRef<Pick<HTMLInputElement, "focus">>(null);
return (
<>
<Form ref={ref} />
<button
onClick={() => {
ref.current?.focus();
}}
type="button"
>
Focus
</button>
</>
);
}
useImperactiveHandleを使うことでfocusのみ呼び出すことができている。
Discussion