
참조(ref)는 React에서 DOM 요소나 클래스형 컴포넌트에 접근하기 위해 사용됩니다.
예를 들어, input 요소에 포커스를 맞추거나, dialog 같은 내장 DOM 요소의 메소드를 호출할 때 사용합니다.
TimerChallenge 컴포넌트에서는 useRef를 사용해 두 개의 참조를 생성합니다:
const timer = useRef();
const dialog = useRef();
function handleStart(){
timer.current = setTimeout(() => {
setTimerExpired(true);
dialog.current.showModal();
//dialog 요소(HTML의 `<dialog>` 태그)를 브라우저에 표시하는 메서드
}, targetTime * 1000);
setTimerStarted(true);
}
<ResultModal ref={dialog} targetTime={targetTime} result="lost"/>
ref={dialog}는 ResultModal 컴포넌트가 dialog라는 참조를 받을 수 있게 해준다
const ResultModal = forwardRef(function ResultModal({ result, targetTime }, ref) {
return (
<dialog ref={ref} className="result-modal">
<h2>You {result}</h2>
<p>The target time was <strong>{targetTime}</strong></p>
<form method="dialog">
<button>Close</button>
</form>
</dialog>
);
});
forwardRef는 ResultModal 컴포넌트를 감싸고 있으며, 이를 통해 부모 컴포넌트(TimerChallenge)에서 전달된 ref를 받아서
<dialog>요소에 연결합니다.
참조(ref): 특정 DOM 요소에 직접 접근하고 조작할 수 있도록 해주는 도구입니다.
useRef 훅: 참조를 생성할 때 사용하며, DOM 요소에 접근하기 위해 사용됩니다.
forwardRef: 참조를 컴포넌트 간에 전달할 수 있도록 해주는 함수입니다.
dialog.current.showModal(): <dialog> DOM 요소를 화면에 표시하기 위해 사용되는 메서드입니다.