본문으로 건너뛰기
yceffort
PostsSeriesTagsAbout🧪 Research
EN

Tweaks

theme
accent palette
film grain
minimal mode
BACK TO INDEX
◆ ESSAY
--min
--year
KOoriginal

mailMail icongithubtwitter
yceffort
•
© 2026
•
https://yceffort.kr
BACK TO INDEX
◆ ESSAY

React 공부하기 5 - Reference

avatar
yceffort
2019-05-09 · 2분
2min
2019year
KOoriginal
react

Reference (Ref)

특정 DOM요소에 작업을 하기 위해서 id를 부여하는 것 처럼, React에서 DOM에 이름을 다는 방식이 있는데 이것이 바로 ref (Reference)다. 반드시, DOM에 직접적으로 접근하여 조작이 필요할 때 만 이용해야 한다.

컴퍼넌트 내부에서 사용

import React, {Component} from 'react'
import './ValidationSample.css'

class ValidationSample extends Component {
  state = {
    password: '',
    clicked: false,
    validated: false,
  }

  handleChange = (e) => {
    this.setState({
      password: e.target.value,
    })
  }

  handleButtonClick = () => {
    this.setState({
      clicked: true,
      validated: this.state.password === '0000',
    })
    this.input.focus()
  }

  render() {
    return (
      <div>
        <input
          ref={(ref) => (this.input = ref)}
          type="password"
          value={this.state.password}
          onChange={this.handleChange}
          className={
            this.state.clicked
              ? this.state.validated
                ? 'success'
                : 'failure'
              : ''
          }
        ></input>
        <button onClick={this.handleButtonClick}>Validation</button>
      </div>
    )
  }
}

export default ValidationSample

중요하게 봐야할 부분은 바로 여기

<input ref="{(ref)" ="" /> this.input=ref}/>

ref 속성을 추가할 때는 props를 설정하듯이 하면 된다. ref 값으로는 콜백 함수를 전달하는데, 이 콜백함수는 ref를 파라미터로 가지며 함수 내부에서 멤버변수에 ref를 담으면 된다. 여기에서는 this.input에 담았다.

this.input.focus()를 통해서 input 태그에 포커스를 달았다.

컴포넌트에 Ref 달기

import React, {Component} from 'react'

class ScrollBox extends Component {
  scrollToBottom = () => {
    const {scrollHeight, clientHeight, width} = 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
import React, {Component} from 'react'
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

ScrollBox에서 scrollToBottom 함수를 정의했다. 그리고 ScrollBox 컴포넌트를 this.scrollBox로 ref를 부여하여 다른 DOM에서 해당 함수를 호출 할 수 있었다.

관련 글

  • #ai#essay#frontend

    프론트엔드는 어디서 왔고, 에이전트 이후 어디로 가는가

    층은 왜 쌓였고, 왜 서버로 돌아왔고, 에이전트 이후에도 스택이 남는 이유는 무엇인가. 그리고 스택이 이기는 것과 그 스택을 아는 사람의 가치는 왜 별개인가

    2026-07-22·34분
  • #react#react-server-components#memoization

    React cache() 딥다이브: 소스 코드로 읽는 요청 단위 메모이제이션

    React cache() 함수의 모든 이상한 규칙은 30여 줄짜리 구현에서 직접 따라 나온다. dispatcher, getCacheForType, WeakMap/Map 트리를 소스 레벨로 따라가며 요청 단위 메모이제이션의 동작을 끝까지 본다.

    2026-05-30·35분
  • ◆ 디렉티브 딥다이브
    #react#nextjs#frontend

    'use cache' 디렉티브 딥다이브: 캐시 경계의 끝까지

    "use cache" 한 줄이 만드는 빌드 타임 변환, 캐시 키 직렬화, ResumeDataCache, cacheHandler, 그리고 Cache Components까지

    2026-05-01·65분
  • ◆ 디렉티브 딥다이브
    #react#nextjs#frontend

    'use client' 디렉티브 딥다이브: 클라이언트 경계의 끝까지

    "use client" 한 줄이 만드는 모듈 경계, 빌드 타임 변환, Flight 직렬화, 그리고 성능까지

    2026-05-01·52분

새 글을 놓치고 싶지 않으시다면 RSS로 구독해 주세요.

RSS 구독 →

yceffort — 프론트엔드 엔지니어입니다. 발표·기술 자문·기고 문의는 이곳에서 받고 있습니다.

← Back to the blogIssue on GitHub →