hooks 에서 ref 사용하기

김영준·2020년 11월 23일
0
post-thumbnail

hooks 에서는 ref를 사용할 수 없는데, 가능하게 해준 것이 바로 useRef 이다.
그리고, 자식 컴포넌트에서 ref를 사용하기 위해선 useImperativeHandle을 사용해야 한다. 사용 예시를 보자.

  • 하고자 하는 것 : 버튼을 누르면 inputfocus를 준다.

간단하게 코드만 정리해본다.

import React, {
  useImperativeHandle,
  forwardRef,
  useRef,
} from "react";

const Component = forwardRef((props, ref) => {
  const buttonRef = useRef();
  useImperativeHandle(ref, () => ({
    special: () => {
      // console.log(buttonRef.current)
      buttonRef.current.focus();
    }
  }));
  return (
    <div>
      <input ref={buttonRef} placeholder="여기로 초점" value="123,000" />
      <button onClick={props.onClick}>{props.children}</button>
    </div>
  );
});

const App = () => {
  const btnRef = useRef();
  const onFocus = () => {
     btnRef.current.special(); 
    }
  
  return (
    <div>
    <Component ref={btnRef} onClick={onFocus} >
    	확인
    </Component>
    </div>
  )
}

export default App;

App 은 부모 컴포넌트이고, Component는 자식 컴포넌트이다.
부모에서 자식으로 btnRefref로 넘겨주고, Componentpropsref를 받아온다. 이때, forwardRef라는 것을 사용해야 refprops 를 받아올 수 있다.
useImperativeHandle를 사용해야 ref를 다룰 수 있다.
useImperativeHandle 안에 special 을 선언한 것 처럼 만들어 준다. 그래야 App 컴포넌트 안에서 onFocus 함수 내부에 btnRef.current.special()을 사용할 수 있다.
주석 처리한 console.log(buttonRef.current)를 살려서 찍어보면,

위와 같이 나타나게 된다.

profile
프론트엔드 개발자 김영준 입니다. 디테일함을 키우고 있습니다

0개의 댓글