useRef()

누리·2022년 10월 14일
0

React Foundation

목록 보기
12/18

Ref란? (Reference)

render 메서드에서 생성된 DOM 노드나 React 엘리먼트에 접근하는 방법을 제공한다
자식 컴포넌트를 부모 컴포넌트에서 접근해야할때 주로 활용되는 요소이다

When to use Ref

  • 포커스, 텍스트 선택영역, 혹은 미디어의 재생을 관리할 때
  • 애니메이션을 직접적으로 실행시킬 때
  • 서드 파티 DOM 라이브러리를 React와 같이 사용할 때

사용방법

useRef() 훅으로 사용되는데 해당 예시를 살펴보자

function TextInputWidthFocusButton(){
  const inputEl = useRef(null);
  const onButtonClick = () => {
    //current : 마운트된 input element를 가르킨다
    inputEl.current.focus();
  };
  
  return (
    <>
     <input ref={inputEl} type="text" />
     <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

useRef 특징

  • 리턴되는 객체의 형태 : current라는 필드를 담고있는 객체를 반환한다
{current : 현재 ref가 담고있는 객체}
  • 리렌더링을 트리거 하지 않는다

input element를 focus하고 싶은데 input element가 마운트 되었을때 굳이 리렌더링 시키지 않아도 되는 상황에서 쓰일 것이다 (DOM element를 직접 접근할때 이런 상황이 발생)

forwardRef : 자식컴포넌트를 컨트롤

//자식컴포넌트
const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

//부모컴포넌트
const ref = React.createRef(); //useRef() 함수와 같은 역할
<FancyButton ref={ref}>Click me!</FancyButton>;

부모 컴포넌트에서 생성한 ref를 자식에게 넘겨줘서 부모컴포넌트에서 작동을 시킨다

callbackRef : 함수를 ref 파라미터에 넘겨주기

setState를 활용해서 ref를 설정할 수 있다

import {useState} from 'react';

const CustomTextInput = () => {
  const [textInput, setTextInput] = useState(null);
  
  const focusTextInput = () => {
    if(textInput) textInput.focus();
  }
  
  return (
    <div>
    	<input 
    		type = "text" 
    		ref = {this.setTextInput}
		/>
    	<input 
			type = "button"
			value = "Focus the text input"
			onClick = {this.focusTextInput}
		/>
    </div>
  );
  
}

useState를 활용하여 ref를 설정했을 때

  • DOM element가 mount되었을때, setState를 통해 ref가 설정되면서 리렌더링됨
  • ref.current 대신 바로 ref로 활용 가능
profile
프론트엔드 개발자

0개의 댓글