React
useImperativeHandle
bkdragon
2024. 11. 27. 21:07
useImperativeHandle
은 ref로 노출되는 핸들을 사용자가 직접 정의할 수 있게 해주는 React 훅이다. 무슨 소리냐면 컴포넌트 내부 함수를 부모 컴포넌트에서 실행할 수 있게 해준다는 소리이다.
import React, { forwardRef, useRef, useImperativeHandle, Ref } from 'react';
interface MyInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
}
export interface MyInputHandle {
focus: () => void;
scrollIntoView: () => void;
}
const MyInput = forwardRef<MyInputHandle, MyInputProps>(function MyInput(
props,
ref: Ref<MyInputHandle>
) {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current?.focus();
},
scrollIntoView() {
inputRef.current?.scrollIntoView();
},
}));
return <input {...props} ref={inputRef} />;
});
export default MyInput;
이제 부모 컴포넌트에서 ref로 focus와 scrollIntoView 를 직접 실행시킬 수 있다.
import React, { useRef } from 'react';
import MyInput, { MyInputHandle } from './MyInput';
function Parent() {
const inputHandleRef = useRef<MyInputHandle>(null);
const handleFocus = () => {
inputHandleRef.current?.focus();
};
const handleScroll = () => {
inputHandleRef.current?.scrollIntoView();
};
return (
<div>
<MyInput ref={inputHandleRef} placeholder="Type something" />
<button onClick={handleFocus}>Focus Input</button>
<button onClick={handleScroll}>Scroll Into View</button>
</div>
);
}
export default Parent;
유연하고 커스텀이 쉽게 컴포넌트를 설계할 수 있다.