Pitfall | 함정

createRef is mostly used for class components. Function components typically rely on useRef instead. createRef는 주로 클래스 컴포넌트에 사용합니다. 함수형 컴포넌트는 일반적으로 useRef에 의존합니다.

createRef creates a ref object which can contain arbitrary value. createRef는 일반적으로 임의의 값을 포함할 수 있는 ref 객체를 만듭니다.

class MyInput extends Component {
inputRef = createRef();
// ...
}

Reference참조

createRef()

Call createRef to declare a ref inside a class component. 클래스 컴포넌트내에서 createRef 를 호출하면 ref를 선언합니다.

import { createRef, Component } from 'react';

class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...

See more examples below. 아래에서 더 많은 예시를 확인하세요.

Parameters매개변수

createRef takes no parameters. createRef 는 매개변수를 받지 않습니다.

Returns반환값

createRef returns an object with a single property: createRef는 단일 속성을 가진 객체를 반환합니다:

  • current: Initially, it’s set to the null. You can later set it to something else. If you pass the ref object to React as a ref attribute to a JSX node, React will set its current property. current: 처음에는 null로 설정되어있습니다. 나중에 다른 것으로 설정할 수 있습니다. ref객체를 JSX노드의 속성으로 React에 전달하면 React가 해당 current 속성을 설정합니다.

Caveats주의사항

  • createRef always returns a different object. It’s equivalent to writing { current: null } yourself. createRef는 항상 다른 객체를 반환합니다. { current: null }이라고 직접 작성하는 것과 같습니다.

  • In a function component, you probably want useRef instead which always returns the same object. 함수형 컴포넌트에서는 createRef 대신 항상 동일한 객체를 반환하는 useRef를 쓰세요.

  • const ref = useRef() is equivalent to const [ref, _] = useState(() => createRef(null)). const ref = useRef()const [ref, _] = useState(() => createRef(null))와 동등합니다.


Usage사용법

Declaring a ref in a class component클래스 컴포넌트에서 ref 선언하기

To declare a ref inside a class component, call createRef and assign its result to a class field: 클래스 컴포넌트내에서 ref를 선언하려면 createRef를 호출하고 해당 결과를 클래스 필드에 할당하세요:

import { Component, createRef } from 'react';

class Form extends Component {
inputRef = createRef();

// ...
}

If you now pass ref={this.inputRef} to an <input> in your JSX, React will populate this.inputRef.current with the input DOM node. For example, here is how you make a button that focuses the input: 이제 JSX에서 ref={this.inputRef}<input>에 전달하면 React가 this.inputRef.current를 입력 DOM 노드로 채웁니다. 예를 들어, 입력에 초점을 맞추는 버튼을 만드는 방법은 다음과 같습니다.

import { Component, createRef } from 'react';

export default class Form extends Component {
  inputRef = createRef();

  handleClick = () => {
    this.inputRef.current.focus();
  }

  render() {
    return (
      <>
        <input ref={this.inputRef} />
        <button onClick={this.handleClick}>
          Focus the input
        </button>
      </>
    );
  }
}

Pitfall | 함정

createRef is mostly used for class components. Function components typically rely on useRef instead. createRef는 주로 클래스 컴포넌트에 사용됩니다. 함수형 컴포넌트는 일반적으로 useRef 에 의존합니다.


Alternatives대안

Migrating from a class with createRef to a function with useRefuseRef 가 있는 클래스에서 useRef가 있는 함수로 마이그레이션하기

We recommend using function components instead of class components in new code. If you have some existing class components using createRef, here is how you can convert them. This is the original code: 새 코드에서는 클래스 컴포넌트 대신 함수형 컴포넌트를 사용하는 것이 좋습니다. createRef를 사용하는 기존 클래스 컴포넌트가 있는 경우 이를 변환할 수 있는 방법은 다음과 같습니다. 아래는 원본 코드입니다.

import { Component, createRef } from 'react';

export default class Form extends Component {
  inputRef = createRef();

  handleClick = () => {
    this.inputRef.current.focus();
  }

  render() {
    return (
      <>
        <input ref={this.inputRef} />
        <button onClick={this.handleClick}>
          Focus the input
        </button>
      </>
    );
  }
}

When you convert this component from a class to a function, replace calls to createRef with calls to useRef: 이 컴포넌트를 클래스에서 함수로 변환할 때, createRef에 대한 호출을 useRef에 대한 호출로 바꿉니다:

import { useRef } from 'react';

export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        Focus the input
      </button>
    </>
  );
}