Written based on React v16.8.4

When to Use Refs

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Creating Refs

React.createRef()를 이용하여 refs를 생성하고, ref attribute를 이용하여 엘리먼트에 추가한다.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

element ID 전달하기

3rd-party library를 사용해야하는 경우에는 해당 element의 id를 전달해야하는 경우에는 아래와 같이 current 속성을 이용하여 전달한다.

import React, { Component } from 'react';
import html2canvas from 'html2canvas';

class App extends Component {
  constructor(props) {
    super(props);
    this.imgRefs = React.createRef();
    this.resultRefs = React.createRef();
  };

  onClickSnapshot = async () => {
    const canvas = await html2canvas(this.imgRefs.current, {
      useCORS: true,
    });
    this.resultRefs.current.appendChild(canvas);
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.onClickSnapshot}>capture</button>
        <div ref={this.imgRefs}>
          <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ4nsgRjLZntKqK6j0kKjHsYJtQQGsLo27TeDJhy3p85qp9m9WB" />
        </div>
        <div ref={this.resultRefs} />
      </div>
    );
  }
}

export default App;