refs and dom When to use Refs React v16.3 이전의 Refs 사용법 React v16.3 이후의 Refs 사용법


Refs provide a way to access DOM nodes or React elements created in the render method.

Refs란, React에서 DOM에 접근할 때 사용하는 방법이다.

When to use Refs


  • input/textarea 등에 focus를 할 때
  • 특정 DOM의 크기를 가져올 때
  • 특정 DOM에서 스크롤 위치를 가져오거나 설정을 할 때
  • 명령형 애니메이션을 발동시킬 때
  • third-party DOM 라이브러리를 통합할 때

React v16.3 이전의 Refs 사용법


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class App extends Component {
constructor(props) {
super(props);
}

handleInput () => {
if (this.myRef.classList.contains("checked")) { // input에 class 관련 적용
Cookie.set("warning-popup", true, {
expires: 1
});
}
}

render() {
return (
<div>
<input ref={ref => (this.myRef = ref)} /> // ref를 input에 적용
</div>
)
}
}

React v16.3 이후의 Refs 사용법


컴포넌트 내에서의 사용법


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class App extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // ref 생성
}

componentDidMount () => {
this.myRef.current.focus(); // 컴포넌트가 첫 렌더링 되면, input에 focus 적용
}

render() {
return (
<div>
<input ref={this.myRef} /> // ref를 input에 적용
</div>
)
}
}

부모 컴포넌트가 자식 컴포넌트 DOM에 접근할 때 사용법


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 부모 컴포넌트
class App extends Component {
constructor(props) {
super(props);
this.childRef = React.createRef(); // ref 생성
}

componentDidMount () => {
this.childRef.current.focus(); // 컴포넌트가 첫 렌더링 되면, input에 focus 적용
}

render() {
return (
<div>
<ChildComponent ref={this.childRef}/> // 자식 컴포넌트에 ref 전달
</div>
)
}
}

// 자식 컴포넌트
const ChildApp = React.forwardRef((props, ref) => { // 부모 컴포넌트로부터 ref 전달 받음
return (
<input ref={ref}/> // input에 ref 적용
)
})