ReactJS - findDOMNode() Method



When using React, we can face situations when we need to access an actual browser DOM node of the component. This is useful for a number of reasons, like working directly with the DOM and integrating third-party libraries that require access to specific elements. We can achieve this by using the findDOMNode method provided by the react-dom package.

What is findDOMNode?

The findDOMNode is a react-dom library method that allows us to locate the browser DOM node linked with a React class component object. In other words, it helps us in identifying the actual HTML element being rendered by our React component.

Syntax

import { findDOMNode } from 'react-dom';
const dn = findDOMNode(componentInstance);

Parameters

componentInstance − It is an instance of a React class component, and domNode will hold the corresponding DOM element.

Return Value

The findDOMNode function returns the first browser DOM node that is closest to the provided componentInstance. However, there are a few factors to consider −

  • findDOMNode will return null if a component renders to null or false.

  • findDOMNode returns a text DOM node with the value of a component that renders to a string.

In addition, if a component provides an array or a Fragment with multiple children, findDOMNode will return the first non-empty child.

Examples

Example − Selecting Input App

When the input text is mounted in a component, we can use the findDOMNode function to automatically choose it. Here's how we can update the app to include the findDOMNode function −

So first we need to create a react app and then we will create a file called SelectingInput.js inside this file we will have a component to use the findDOMNode function to automatically select the text inside the input field when it's mounted.

Now, the App component will use the SelectingInput component when we click the "Show the Input" button. The input field inside the SelectingInput component will automatically select its text after mounting.

SelectingInput.js

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

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

export default SelectingInput;

App.js

import React, { useState } from 'react';
import SelectingInput from './SelectingInput';

function App() {
   const [show, setShow] = useState(false);
   
   return (
      <>
         <button onClick={() => setShow(true)}>Show the input</button>
         <hr />
         {show && <SelectingInput />}
      </>
   );
}

export default App;

Output

show the input

This example shows how to interact with the DOM when a component mounts in a React app using the findDOMNode function.

Example − Render a String

In this example we will create a basic React application consisting of two components: App and MyComponent. It is a class component that extends the Component class provided by React. The render method returns an <h1> HTML element with the text "This is a simple string." App Component is the main component of our app. In the componentDidMount lifecycle method, it uses the findDOMNode function to get the actual DOM node. The obtained DOM node is then logged to the console. In the render method of the App component, an instance of MyComponent is rendered inside a <div>.

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

class MyComponent extends Component {
   render() {
      return <h1>This is a simple string</h1>; // Rendering to string
   }
}
class App extends Component {
   componentDidMount() {
      const domNode = findDOMNode(this.myComponentInstance);
      console.log(domNode);
   }   
   render() {
      return (
         <div>
            <MyComponent ref={(component) => (this.myComponentInstance = component)} />
         </div>
      );
   }
}

export default App;

Output

simple string

When this app is run, it will render a simple <h1> element with the text "This is a simple string." The componentDidMount lifecycle method of the App component will then log the associated DOM node of MyComponent to the console.

Example − Counter App

Here is another simple React app that utilizes the findDOMNode function. We will have a Counter Component which is a class component that maintains a count state. It has a button to increment the count when clicked. The componentDidMount method logs the related DOM node to the console. And our main component is an App which renders the Counter component inside a <div> and uses the ref attribute to get a reference to the Counter instance.

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

class Counter extends Component {
   constructor() {
      super();
      this.state = {
         count: 0,
      };
   }   
   handleIncrement = () => {
      this.setState((prevState) => ({ count: prevState.count + 1 }));
   };   
   componentDidMount() {
      const domNode = findDOMNode(this.counterInstance);
      console.log(domNode);
   }   
   render() {
      return (
         <div>
            <h1>Counter: {this.state.count}</h1>
            <button onClick={this.handleIncrement}>Increment</button>
         </div>
      );
   }
}
class App extends Component {
   render() {
      return (
         <div>
            <Counter ref={(component) => (this.counterInstance = component)} />
         </div>
      );
   }
}

export default App;

Output

counter 4 increment

So when we click the "Increment" button, the count increases. In the console, we will see the associated DOM node of the Counter component logged when the component mounts.

Summary

findDOMNode is a useful tool for filling the gap between the React virtual DOM and the actual browser DOM. But we should use it with care and look for different methods when possible, as directly accessing the DOM in our React application can result in unexpected behavior.

reactjs_reference_api.htm
Advertisements