1 minute read

In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props.

However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element.

Use ref

  • 포커스, 텍스트 선택영역, 혹은 미디어의 재생을 관리할 때
  • 애니메이션을 직접적으로 실행시킬 때.
  • 서드 파티 DOM 라이브러리를 React와 같이 사용할 때.


Create ref

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

How to access to the ref

const node = this.myRef.current;


Use in real project

1) Create imageRef 2) Set componentDidMount to get a data after rendering 3) Add addEventListener with Vanlia JS to run code after load all image

class ImageCard extends React.Component {
  constructor(props) {
    super(props);
    this.imageRef = React.createRef();
  }

  // after creating Component, finishing first rendering, it runs
  componentDidMount() {
    this.imageRef.current.addEventListener('load', this.setSpans);
  }

  setSpans = () => {
    console.log(this.imageRef.current.height);
  };

  render() {
    const { urls, description } = this.props.image;

    return (
      <div>
        <img ref={this.imageRef} src={urls.regular} alt={description} />
      </div>
    );
  }
}

export default ImageCard;

Categories:

Updated: