HTML과 비교해보면 쉽다.
HTML을 작성할 때 이렇게 id를 붙이는 것처럼, 리액트에서도 DOM을 선택해 직접 접근하기 위해 ref를 사용한다.
즉, ref는 DOM에 직접 접근하기 위한 도구이다.
React에서 state로만 해결할 수 없고, DOM을 반드시 직접 건드려야 할 때 사용하게 된다.
ex) 특정 input에 focus 주기, 스크롤 박스 조작, Canvas 요소에 그림 그리기 등…
import { useRef } from 'react';
import domtoimage from 'dom-to-image'
...
const TestComponent = (props) => {
const {id, nickName} = props;
const personInfo = useRef();
const onClick = function () {
domtoimage.toPng(personInfo.current)
.then(function (blob) {
window.saveAs(blob, 'user-card.png');
})
};
return (
<>
<div className="box" ref={personInfo}>
<p> {id} - {nickName} 테스트 영역 </p>
</div>
<button onClick={onClick}>저장</button>
</>
);
}
const personInfo = useRef(); 를 통해 personInfo에 ref 객체를 반환한다.
div.box 요소에 ref={personInfo} 값을 부여
personInfo.current를 하면, 위에서 부여한 div 요소에 접근 가능한 id처럼 사용할 수 있다.
(personInfo.current는 이 div 요소를 가리킴)
ref를 달고자 하는 요소에, ref라는 콜백 함수를 props로 전달해 준다.
이 콜백 함수는 ref 값을 파라미터로 전달받으며, 함수 내부에서 파라미터로 받은 ref를 컴포넌트의 멤버 변수로 설정한다.
<input
ref={(ref) => {
this.input = ref;
}}
/>
즉, 리액트 내에서 id 처럼 쓰이게 된 것이다.
ref를 DOM 요소에 다는 것 말고도 컴포넌트에도 달 수 있다.
컴포넌트 내부의 DOM 요소를 컴포넌트 외부에서 사용해야 할 때 활용
<MyComponent
ref={(ref) => {
this.myComponent = ref;
}}
/>
DOM 요소에 다는 방법이랑 똑같다고 보면 된다.
return (
<div>
<ScrollBox ref={(ref) => (this.scrollBox = ref)} />
<button onClick={() => this.scrollBox.ScrollToBottom()}>
맨 밑으로
</button>
</div>
);
ScrollBox 컴포넌트에 ref를 달았고, 그 밑에 button에서 this.scrollBox.ScrollToBottom()처럼 내부 메서드에 접근했다.