findDOMNode()
findDOMNode() was very popular for returning the DOM of any element in the class-based component. But after React v16.3 it was discouraged but till now it is used for certain use cases. But there is a chance that it might get removed from the future version of React.
If the component renders a null value then, in that case, it returns a null value and if the component will render a string value then, in that case, it will return that value.
Syntax:
ReactDOM.findDOMNode(Instance of the component);
Steps to use findDOMNode():
- Make a js file in the src folder. let us say “Gfg.js”
- Make a class component “Gfg” and export that.
- After that import that component into our App.js and use it there
- Now in our Gfg component make an element let us say div with some text and with an id.
- After that import “ReactDOM” from “react-dom” in that Gfg.js
- Make a method in that class component. let us say we made manDOM() method.
- In that method select that element by “getElementById” and then select that by ReactDOM.findDOMNode()
- After that do whatever changes you want to apply on the DOM of this element
- So here we are adding the background color of that element as “yellow” by calling that method on a button click.
Example:
Javascript
import React from "react" ; import ReactDOM from "react-dom" ; class Gfg extends React.Component { manDOM = () => { var ele = document.getElementById( "mydiv" ); var a = ReactDOM.findDOMNode(ele); a.style.backgroundColor = "yellow" ; }; render() { return ( <> <h1 className= "gfg" >w3wiki</h1> <h3 className= "gfgdom" >findDOMNode() in React</h3> <div id= "mydiv" >Testing</div> <button onClick={ this .manDOM}>Change</button> </> ); } } export default Gfg; |
Steps to Run the application: After that run your application using the following command:
npm start
Output:
Which is preferred option with in callback refs and findDOMNode() in ReactJS ?
ReactJS employs two prominent concepts, namely callback refs and `findDOMNode()`, for effective DOM manipulation. These mechanisms facilitate access to DOM elements, enabling the implementation of diverse changes such as hiding or showing elements, altering styles, and focusing on specific elements.
Table of Content
- findDOMNode()
- Callback refs