Deprecated | 지원 중단

This API will be removed in a future major version of React. See the alternatives. 이 API는 향후 React의 주요 버전에서 제거될 예정입니다. 대안을 확인하세요.

findDOMNode finds the browser DOM node for a React class component instance. findDOMNode는 React 클래스 컴포넌트 인스턴스에 대한 브라우저 DOM 노드를 찾습니다.

const domNode = findDOMNode(componentInstance)

Reference참조

findDOMNode(componentInstance)

Call findDOMNode to find the browser DOM node for a given React class component instance. findDOMNode를 호출하면 주어진 React 클래스 컴포넌트 인스턴스에 대한 브라우저 DOM 노드를 찾습니다.

import { findDOMNode } from 'react-dom';

const domNode = findDOMNode(componentInstance);

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

Parameters매개변수

  • componentInstance: An instance of the Component subclass. For example, this inside a class component. componentInstance: Component 서브 클래스의 인스턴스. 예: 컴포넌트 클래스 내부의 this.

Returns반환값

findDOMNode returns the first closest browser DOM node within the given componentInstance. When a component renders to null, or renders false, findDOMNode returns null. When a component renders to a string, findDOMNode returns a text DOM node containing that value. findDOMNode는 주어진 componentInstance 내에서 가장 가까운 첫 번째 브라우저 DOM 노드를 반환합니다. 컴포넌트가 null 또는 false로 렌더링되면 findDOMNodenull을 반환합니다. 컴포넌트가 문자열로 렌더링되면 findDOMNode는 해당 값을 포함하는 텍스트 DOM 노드를 반환합니다.

Caveats주의사항

  • A component may return an array or a Fragment with multiple children. In that case findDOMNode, will return the DOM node corresponding to the first non-empty child. 컴포넌트는 여러 자식이 있는 배열 또는 Fragment를 반환할 수 있습니다. 이 경우 findDOMNode는 비어 있지 않은 첫 번째 자식에 해당하는 DOM 노드를 반환합니다.

  • findDOMNode only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling findDOMNode() in render() on a component that has yet to be created), an exception will be thrown. findDOMNode는 마운트 된 컴포넌트(즉, DOM에 배치된 컴포넌트)에 대해서만 작동합니다. 아직 마운트 되지 않은 컴포넌트에서 이 함수를 호출하려고 하면(예: 아직 생성되지 않은 컴포넌트의 render()에서 findDOMNode()를 호출하는 경우) 예외를 던집니다.

  • findDOMNode only returns the result at the time of your call. If a child component renders a different node later, there is no way for you to be notified of this change. findDOMNode는 호출 시점의 결과만 반환합니다. 자식 컴포넌트가 나중에 다른 노드를 렌더링하는 경우, 해당 변경 사항을 알 수 있는 방법은 없습니다.

  • findDOMNode accepts a class component instance, so it can’t be used with function components. findDOMNode는 클래스 컴포넌트 인스턴스만 받으며, 함수 컴포넌트에 사용할 수는 없습니다.


Usage사용법

Finding the root DOM node of a class component클래스 컴포넌트의 루트 DOM 노드 찾기

Call findDOMNode with a class component instance (usually, this) to find the DOM node it has rendered. 클래스 컴포넌트 인스턴스(보통 this)로 findDOMNode를 호출하여 렌더링된 DOM 노드를 찾습니다.

class AutoselectingInput extends Component {
componentDidMount() {
const input = findDOMNode(this);
input.select()
}

render() {
return <input defaultValue="Hello" />
}
}

Here, the input variable will be set to the <input> DOM element. This lets you do something with it. For example, when clicking “Show example” below mounts the input, input.select() selects all text in the input: 여기서 input 변수는 <input> DOM 요소로 설정됩니다. 이를 통해 무언가를 할 수 있습니다. 예를 들어, 아래의 “예제 표시”를 클릭하면 input이 마운트되고, input.select()는 input의 모든 텍스트를 선택합니다:

import { Component } from 'react';
import { findDOMNode } from 'react-dom';

class AutoselectingInput extends Component {
  componentDidMount() {
    const input = findDOMNode(this);
    input.select()
  }

  render() {
    return <input defaultValue="Hello" />
  }
}

export default AutoselectingInput;


Alternatives대안

Reading component’s own DOM node from a refref에서 컴포넌트의 자체 DOM 노드 읽기

Code using findDOMNode is fragile because the connection between the JSX node and the code manipulating the corresponding DOM node is not explicit. For example, try wrapping this <input /> into a <div>: findDOMNode를 사용하는 코드는 JSX 노드와 해당 DOM 노드를 조작하는 코드 사이의 연결이 명시적이지 않기 때문에 취약합니다. 예를 들어, 이 예제의 <input /><div>로 감싸봅시다:

import { Component } from 'react';
import { findDOMNode } from 'react-dom';

class AutoselectingInput extends Component {
  componentDidMount() {
    const input = findDOMNode(this);
    input.select()
  }
  render() {
    return <input defaultValue="Hello" />
  }
}

export default AutoselectingInput;

This will break the code because now, findDOMNode(this) finds the <div> DOM node, but the code expects an <input> DOM node. To avoid these kinds of problems, use createRef to manage a specific DOM node. 이제 findDOMNode(this)<div> DOM 노드를 찾지만, 코드에서는 <input> DOM 노드를 기대하기 때문에 코드가 손상됩니다. 이러한 종류의 문제를 방지하려면 createRef를 사용하여 특정 DOM 노드를 관리하세요.

In this example, findDOMNode is no longer used. Instead, inputRef = createRef(null) is defined as an instance field on the class. To read the DOM node from it, you can use this.inputRef.current. To attach it to the JSX, you render <input ref={this.inputRef} />. This connects the code using the DOM node to its JSX: 다음 예제에서는 더이상 findDOMNode를 사용하지 않습니다. 대신 inputRef = createRef(null)를 클래스의 인스턴스 필드로 정의했습니다. 이 필드에서 DOM 노드를 읽으려면 this.inputRef.current를 사용할 수 있습니다. 이를 JSX에 첨부하고자 <input ref={this.inputRef} />를 렌더링했습니다. 이를 통해 DOM 노드로 코드를 JSX에 연결했습니다:

import { createRef, Component } from 'react';

class AutoselectingInput extends Component {
  inputRef = createRef(null);

  componentDidMount() {
    const input = this.inputRef.current;
    input.select()
  }

  render() {
    return (
      <input ref={this.inputRef} defaultValue="Hello" />
    );
  }
}

export default AutoselectingInput;

In modern React without class components, the equivalent code would call useRef instead: 클래스 컴포넌트가 없는 최신 React에서 이와 동등한 코드는 useRef를 호출하는 것입니다:

import { useRef, useEffect } from 'react';

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

  useEffect(() => {
    const input = inputRef.current;
    input.select();
  }, []);

  return <input ref={inputRef} defaultValue="Hello" />
}

Read more about manipulating the DOM with Refs. ref로 DOM을 조작하기에서 자세히 알아보세요.


Reading a child component’s DOM node from a forwarded ref전달된 ref에서 자식 컴포넌트의 DOM 노드 읽기

In this example, findDOMNode(this) finds a DOM node that belongs to another component. The AutoselectingInput renders MyInput, which is your own component that renders a browser <input>. 다음 예제에서 findDOMNode(this)는 다른 컴포넌트에 속하는 DOM 노드를 찾습니다. AutoselectingInput은 브라우저 <input>을 렌더링하는 자체 컴포넌트인 MyInput을 렌더링합니다.

import { Component } from 'react';
import { findDOMNode } from 'react-dom';
import MyInput from './MyInput.js';

class AutoselectingInput extends Component {
  componentDidMount() {
    const input = findDOMNode(this);
    input.select()
  }
  render() {
    return <MyInput />;
  }
}

export default AutoselectingInput;

Notice that calling findDOMNode(this) inside AutoselectingInput still gives you the DOM <input>—even though the JSX for this <input> is hidden inside the MyInput component. This seems convenient for the above example, but it leads to fragile code. Imagine that you wanted to edit MyInput later and add a wrapper <div> around it. This would break the code of AutoselectingInput (which expects to find an <input>). <input>에 대한 JSX가 MyInput 컴포넌트 안에 숨겨져 있더라도, AutoselectingInput 내부에서 findDOMNode(this)를 호출하면 여전히 DOM <input>이 반환된다는 점에 유의하세요. 이것은 위의 예제에서는 편리해 보이지만, 코드가 취약해질 수 있습니다. 나중에 MyInput을 편집한 뒤 이를 감싸는 <div>를 추가하고 싶다고 상상해 봅시다. 이렇게 하면 AutoselectingInput(<input> DOM 노드를 찾을 것으로 예상됨)의 코드가 중단됩니다.

To replace findDOMNode in this example, the two components need to coordinate: 이 예제에서 findDOMNode를 대체하려면 두 컴포넌트를 조정해야 합니다:

  1. AutoSelectingInput should declare a ref, like in the earlier example, and pass it to <MyInput>. 앞의 예제에서와 같이 AutoSelectingInput은 ref를 선언하고 이를 <MyInput>에 전달해야 합니다.

  2. MyInput should be declared with forwardRef to take that ref and forward it down to the <input> node. MyInput은 전달받은 ref를 읽어 <input>노드로 전달하기 위해 forwarRef와 함께 선언해야 합니다.

This version does that, so it no longer needs findDOMNode: 다음 코드는 이를 수행하므로 더이상 findDOMNode가 필요하지 않습니다:

import { createRef, Component } from 'react';
import MyInput from './MyInput.js';

class AutoselectingInput extends Component {
  inputRef = createRef(null);

  componentDidMount() {
    const input = this.inputRef.current;
    input.select()
  }

  render() {
    return (
      <MyInput ref={this.inputRef} />
    );
  }
}

export default AutoselectingInput;

Here is how this code would look like with function components instead of classes: 다음은 위 코드를 클래스가 아닌 함수 컴포넌트에 적용한 사례입니다:

import { useRef, useEffect } from 'react';
import MyInput from './MyInput.js';

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

  useEffect(() => {
    const input = inputRef.current;
    input.select();
  }, []);

  return <MyInput ref={inputRef} defaultValue="Hello" />
}


Adding a wrapper <div> element감싸는 <div> 추가하기

Sometimes a component needs to know the position and size of its children. This makes it tempting to find the children with findDOMNode(this), and then use DOM methods like getBoundingClientRect for measurements.컴포넌트는 자식의 위치와 크기를 알아야 하는 경우가 있습니다. 이 때문에 findDOMNode(this)로 자식을 찾은 다음 getBoundingClientRect와 같은 DOM 메서드를 사용해 측정하고 싶은 유혹을 느끼게 됩니다.

There is currently no direct equivalent for this use case, which is why findDOMNode is deprecated but is not yet removed completely from React. In the meantime, you can try rendering a wrapper <div> node around the content as a workaround, and getting a ref to that node. However, extra wrappers can break styling. 아직까지는 이 사용 사례에 직접적으로 대응하는 것이 없기 때문에, findDOMNode는 비록 지원은 중단되었지만 아직 React에서 완전히 제거되지는 않았습니다. 대신 콘텐츠 주위를 <div>로 감싸고, 이 div에 대한 ref를 가져오는 방식으로 우회할 수 있습니다. 다만 이렇게 감싸는 노드를 추가하는 경우 스타일을 손상시키는 경우가 있을 수 있습니다.

<div ref={someRef}>
{children}
</div>

This also applies to focusing and scrolling to arbitrary children. 이는 임의의 자식 요소에 초점을 맞추거나 스크롤 하는 경우에도 적용됩니다.