
개발환경
- react - v17.0.2
- typescript - v4.3.2
reference의 줄임말로, DOM을 직접 참조하기 위해 사용한다. 클래스형 컴포넌트에서는 createRef, 함수형 컴포넌트에서는 useRef를 사용하는데, 둘의 동작 방식은 동일하다.
HTML에서 id를 사용하여 DOM에 이름을 다는 것처럼 리액트 프로젝트 내부에서 DOM에 이름을 다는 방법
크게 보자면 DOM을 직접적으로 건드려야 할 때인데, 아래의 상황에서 사용한다.
편의상(?) styled-components를 활용했다.
$ yarn add styled-components @types/styled-components
변수.current를 통해 해당 DOM을 조작한다.import React from 'react';
import styled from 'styled-components';
const OuterBox = styled.div`
border: 1px solid black;
height: 300px;
width: 300px;
overflow: auto;
position: relative;
`;
const InnerBox = styled.div`
width: 100%;
height: 650px;
background: 'linear-gradient(white, black)';
`;
function ScrollBox() {
const boxRef = React.useRef<any>(); // ref 변수 선언
console.log(boxRef.current.scrollHeight, boxRef.current.clientHeight);
// DOM 조작 함수
const scrollToBottom = () => {
const { scrollHeight, clientHeight } = boxRef.current;
boxRef.current.scrollTop = scrollHeight - clientHeight;
};
return (
<>
<h1>ref 연습2</h1>
<OuterBox ref={boxRef}>
<InnerBox />
</OuterBox>
<button type="button" onClick={scrollToBottom}>
맨 밑으로
</button>
</>
);
}
export default ScrollBox;
맨 밑으로 클릭 전
맨 밑으로 버튼 클릭 시
맨 밑으로 버튼을 클릭하면 useRef로 찍은 DOM(outerBox)의 scrollTop 속성을 직접적으로 조작하는 것을 볼 수 있다. 실제 javascript 코드에서 document.querySelector('#id')로 DOM을 콕 찍어 조작하는 것과 똑같이 동작한다.