render 메서드에서 생성된 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>
</>
);
}
- 리턴되는 객체의 형태 : current라는 필드를 담고있는 객체를 반환한다
{current : 현재 ref가 담고있는 객체}
- 리렌더링을 트리거 하지 않는다
input element를 focus하고 싶은데 input element가 마운트 되었을때 굳이 리렌더링 시키지 않아도 되는 상황에서 쓰일 것이다 (DOM element를 직접 접근할때 이런 상황이 발생)
//자식컴포넌트
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를 자식에게 넘겨줘서 부모컴포넌트에서 작동을 시킨다
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
로 활용 가능