React
forwardRef
bkdragon
2024. 11. 20. 20:54
React에서 useRef로 DOM 요소에 대한 참조를 얻을 수 있다. 근데 ref는 컴포넌트에는 사용할 수 없는데 그 이유는 컴포넌트는 DOM 요소를 반환하는 함수이기 때문이다. 그래서 컴포넌트에 ref를 넘기려면 forwardRef 가 필요하다.
import React, { forwardRef, Ref } from 'react';
interface MyInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
}
const MyInput = forwardRef<HTMLInputElement, MyInputProps>(
(props, ref: Ref<HTMLInputElement>) => {
return <input {...props} ref={ref} />;
}
);
MyInput.displayName = "MyInput";
export default MyInput;
forwardRef로 감싸서 컴포넌트를 만들면 된다. 이렇게 하면 부모 컴포넌트에서 input 을 직접 조작할 수 있다.
import React, { useRef } from 'react';
import MyInput from './MyInput';
function Parent() {
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<MyInput ref={inputRef} placeholder="Type something" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default Parent;