forwardRef()
는 React 컴포넌트에 ref prop을 넘겨서 그 내부에 있는 HTML 엘리먼트에 접근을 하게 해줍니다.
import React, { forwardRef, useRef } from "react";
const Input = forwardRef((props, ref) => {
return <input type="text" ref={ref} />;
});
function Field() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current.focus();
}
return (
<>
<Input ref={inputRef} />
<button onClick={handleFocus}>입력란 포커스</button>
</>
);
}