버튼을 클릭하면 input에 focus를 주고싶다면?
input이 아닌 input태그를 담은 하나의 컴포넌트로 만들어져있다면 같은 기능을 어떻게 구현할까?
- 이때 사용할 수 있는게 forwardRef임
부모 컴포넌트
import { useRef } from "react";
import MyInput from "../components/MyInput";
function ForwardRef() {
const inputRef = useRef();
const focus = () => {
inputRef.current.focus();
};
return (
<div>
<MyInput ref={inputRef} />
<button onClick={focus}>집중</button>
</div>
);
}
export default ForwardRef;
자식 컴포넌트
import { forwardRef } from "react";
const MyInput = (props, ref) => {
return <input ref={ref}></input>;
};
export default forwardRef(MyInput);
import React, { forwardRef } from "react";
const MyInput = forwardRef((props, ref) => {
return <input ref={ref}></input>;
});
export default MyInput;