Ref는 render 메서드에서 생성된 DOM 노드나 React 엘리먼트에 접근하는 방법을 제공합니다.
React의 ref prop은 HTML 엘리먼트의 레퍼런스를 변수에 저장하기 위해서 사용합니다.
예를 들어, 다음과 같이 input
엘리먼트에 ref prop으로 inputRef라는 변수를 넘기게 되면, 우리는 이 inputRef 객체의 current 속성을 통해서 input
엘리먼트에 접근할 수 있고, DOM API를 이용하여 제어할 수 있습니다.
<input ref={inputRef} />
ref prop에는 React API를 이용해서 생성한 current 속성을 갖는 특정 형태의 객체만을 할당할 수 있는데요. 클래스 기반 컴포넌트를 에서는 React.createRef() 함수를, 함수형 컴포넌트에서는 useRef() 훅(hook) 함수를 사용하여 이 객체를 생성할 수 있습니다.
버튼을 클릭했을 때, 비활성화(disabled)되어 있던 입력란을 활성화시키며 포커스(focus)를 이동시키는 React 컴포넌트
useRef 훅(hook)함수를 사용하여 inputRef 객체를 생성한다.
input
엘리먼트에 ref prop를 넘긴다.
이렇게 하면 inputRef 객체의 current 속성에는 input
엘리먼트의 레퍼런스가 저장된다.
따라서 button
엘리먼트의 클릭(click) 이벤트 핸들러에서는 inputRef.current로 간단하게 input
엘리먼트를 제어할 수 있다.
import React, { useRef } from "react";
function Field() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current.disabled = false;
inputRef.current.focus();
}
function handleReset() {
inputRef.current.disabled = true;
inputRef.current.value = "";
}
return (
<>
<input disabled type="text" ref={inputRef} />
<button onClick={handleFocus}>활성화</button>
<button onClick={handleReset}>초기화</button>
</>
);
}