패스트캠퍼스 데브캠프

김민태의 데브캠프 2기 - Forward Ref에 대해 알아보자

vitamin3000 2024. 11. 13. 21:21

자바스크립트에서 input에 focus를 주고 싶을때는 어떻게 하면 될까?

 

document.getElementById("focusButton").addEventListener("click", () => {
   document.getElementById("myTextField").focus();
});

 

그렇다면 리액트에선 ? 

 

const inputRef = useRef();

const handleClick = () => {
	inputRef.current.focus();
}

<input ref={inputRef}/>
<button onClick={handleClick>클릭</button>

 

만약 자녀 컴포넌트에 input이 있다면?

오류 발생!

왜냐하면 ref는 예약어이기 때문에 props처럼 "내려"줄 수 없다.

이럴 때 사용하는 것이 forwardRef이다.

사용 방법은 자녀 컴포넌트에서 export할 때 감싸주면 된다.

 

export default forwardRef(ChildComponent);