본문 바로가기
JavaScript/React

React) ref - 컴포넌트에 이름 달기

by 박채니 2022. 11. 11.
안녕하세요, 코린이의 코딩 학습기 채니 입니다.
[리액트를 다루는 기술]의 책을 참고하여 포스팅한 개인 공부 내용입니다.

 

 

컴포넌트에 ref 달기

주로 컴포넌트 내부에 있는 DOM을 컴포넌트 외부에서 사용할 때 씁니다.

 

 

사용법

<MyComponent ref={(ref) => {this.myComponent = ref}} />

이렇게 설정하면, MyComponent 내부의 메소드 및 멤버 변수, ref에도 접근할 수 있습니다.

 

이를 이용해

스크롤 박스가 있는 컴포넌트를 하나 만들고, 스크롤바를 아래로 내리는 작업을 부모 컴포넌트에서 실행해보겠습니다.


컴포넌트 초기 설정

 

스크롤 박스 컴포넌트 파일 생성

 

ScrollBox.js

import { Component } from "react";

class ScrollBox extends Component {
    render() {
        const style = {
            border: '1px solid black',
            height: '300px',
            width: '300px',
            overflow: 'auto',
            position: 'relative'
        };

        const innerStyle = {
            width: '100%',
            height: '650px',
            background: 'linear-gradient(white, black)'
        };

        return(
            <div style={style} ref={(ref) => {this.box = ref}}>
                <div style={innerStyle} />
            </div>
        );
    }
}

export default ScrollBox;

 

 

App 컴포넌트에서 스크롤 박스 컴포넌트 렌더링

 

App.js

import { Component } from 'react';
import './App.css'
import ScrollBox from './ScrollBox';

class App extends Component {
  render() {
    return (
      <div>
        <ScrollBox />
      </div>
    )
  }
}

export default App;

잘 렌더링 되는 것을 확인할 수 있습니다.

 

 

컴포넌트에 메소드 설정

 

스크롤바를 맨 아래쪽으로 내리는 메소드를 생성할 것이고, 아래 값들을 사용할 겁니다.

  • scrollTop : 세로 스크롤바 위치 (0~350)
  • scrollHeight : 스크롤이 있는 박스 안의 div 높이(650)
  • clientHeight : 스크롤이 있는 박스의 높이 (300)

 

ScrollBox.js - scrollToBottom 메소드 추가

import { Component } from "react";

class ScrollBox extends Component {

    scrollToBottom = () => {
        console.log(this.box); // ref를 가리킴
        const { scrollHeight, clientHeight} = this.box;
        this.box.scrollTop = scrollHeight - clientHeight;
    }

    render() {
        const style = {
            border: '1px solid black',
            height: '300px',
            width: '300px',
            overflow: 'auto',
            position: 'relative'
        };

        const innerStyle = {
            width: '100%',
            height: '650px',
            background: 'linear-gradient(white, black)'
        };

        return(
            <div style={style} ref={(ref) => {this.box = ref}}>
                <div style={innerStyle} />
            </div>
        );
    }
}

export default ScrollBox;

scrollToBottom 메소드를 생성하였고 이는 부모 컴포넌트에서 ScrollBox에 ref를 달면 사용 가능합니다.

 

 

컴포넌트에 ref 달고 내부 메소드 사용

 

App.js

import { Component } from 'react';
import './App.css'
import ScrollBox from './ScrollBox';

class App extends Component {
  render() {
    return (
      <div>
        <ScrollBox ref={(ref) => {this.scrollBox = ref}} />
        <button onClick={() => {this.scrollBox.scrollToBottom()}}>아래로</button>
      </div>
    )
  }
}

export default App;

 

여기서 onClick시 scrollToBottom 함수 실행 시 onClick = {this.scrollBox.scrollToBottom}으로 해야할 것 같지만,

컴포넌트가 처음 렌더링될 때 this.scrollBox가 undefined이므로 this.scrollBox.scrollToBottom을 불러오는 과정에서 오류가 발생하게 됩니다.

따라서 화살표 함수를 이용해 새로운 함수 안에서 scrollToBottom 메소드를 실행해주어 버튼을 누를 때 this.scrollBox.scrollToBottom 값을 읽어와 실행하게 시켜 오류를 방지해 줍니다.

 

 

※ 컴포넌트끼리 데이터를 공유할 때는 언제나 데이터를 부모 ↔ 자식 흐름으로 교류!