React 와 DOM

nona·2021년 1월 9일
0

React

목록 보기
2/7

DOM 에 접근하기 위해 vanila javascript에서는 document.querySelector를 쓴다면, React에는 Ref를 쓴다!

React Refs

ref의 특징: single DOM element에 접근할 수 있게 해준다.

과정

  1. constructor function안에서 ref를 만든다.
  2. 그 ref를 instance variable로 선언한다.
  3. 그 ref를 JSX에 props로 전달해준다.

예시

class ImageCard extends React.Component {
  constructor(props) {
    super(props);

    this.imageRef = React.createRef();
  }

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

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

응용

이렇게 접근한 DOM element에 CSS grid 스타일링을 넣어보자

/* ImageList.css */
.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-gap: 0 10px;
  grid-auto-rows: 10px;
}

.image-list img {
  width: 250px;
  grid-row-end: span 2;
}
import React from 'react';

class ImageCard extends React.Component {
  constructor(props) {
    super(props);

    this.state = { spnas: 0 };

    this.imageRef = React.createRef();
  }

  componentDidMount() {
    this.imageRef.current.addEventListener('load', this.setSpans);
  }

  setSpans = () => {
    const height = this.imageRef.current.clientHeight;

    const spans = Math.ceil(height / 10);

    this.setState({ spans });
  }

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

    return (
      <div style={{ gridRowEnd: `span ${this.state.spans}` }}>
        <img ref={this.imageRef} alt={description} src={urls.regular} />
      </div>
    );
  }
}

export default ImageCard;

0개의 댓글