Updated April 3, 2023
Introduction to React DOM findDOMNode
FindDOMNode works as an escape hatch that helps in accessing the DOM node. Generally, it is advised to avoid this escape hatch as it pierces the abstraction of the component. If a ReactDOM.findDOMNode (component) is mounted in the DOM then the corresponding native browser DOM element is returned. This method generally helps us to read out the values of the DOM like the DOM measurements and the form field values. In this article, we will briefly introduce you to the different React DOM methods and especially about React DOM findDOMNode. There are different examples of React DOM findDOMNode in the article below.
Working of React Dom Finddomnode
Different DOM specific methods are provided by the react-dom package. This method is used as an escape hatch at the top level of the application. The methods are:
1. render(): This method is used to render an element of React in the DOM. It returns a component’s reference. If the react element was already rendered earlier then this will update the DOM as per the latest up-gradation to the element. Any optional callback will get executed after rendering or upgrading.
2. hydrate(): It is expected by React that the server and the client will have identical rendered content. The differences in the text content can be patched up but the mismatches should be fixed as they will get considered as a bug. Generally, you will get warned about the mismatches in hydration during the development mode.
3. unmountComponentAtNode(): This method cleans up the event handlers and the state, it even removes the react component mounted in the DOM. If there wasn’t any component mounted in theDOM then this method does nothing. A true is returned when a component gets unmounted and a False if no component exists to unmount.
4. findDOMNode(): This method returns a corresponding native browser DOM element to the component mounted. It is generally used to read out the values of DOM like the DOM measurements and the form field values. If a null or false value is rendered by the component, a null value is returned by the findDOMNode as well. Similarly, if a component renders a string value then the finfDOMNode returns a text DOM node that contains the value.
5. createPortal(): This method creates a portal that helps in rendering the children who are outside the DOM Component’s hierarchy into the DOM node.
findDOMNode works as an escape hatch which helps in accessing the DOM node. The use of this escape hatch has been advised to avoid as it pierces the abstraction of the component. findDOMNode is defined to work only on the mounted components and if it is called on a component that is not mounted yet then it throws an exception.
React DOM Finddomnode Examples
Below are the different examples of React Dom Finddomnode:
Example #1 – With Input Element
In the example below, we have used ReactDOM.findDOMNode(this) to display the props using data-dom-value which toggles between the current prop and previous prop.
The files used to implement the code below are:
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class Input extends React.Component {
componentDidMount() {
this.el = ReactDOM.findDOMNode(this);
this.el.value = this.props["data-dom-value"];
}
componentDidUpdate(prevProps) {
let value = this.props["data-dom-value"];
if (prevProps["data-dom-value"] !== value) {
this.el.value = value;
}
}
render() {
return <input type={this.props.type} value="123" onChange={() => {}} />;
}
}
function App() {
return (
<>
<h1>Welcome to our Page!</h1>
<Input type="number" data-dom-value={416} />
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
styles.css
.App {
font-family: times;
text-align: center;
}
input {
font-size: serif;
}
Output:
Example #2 – Trapping Values with React DOM Finddomnode
In the example below, at the initial stage, the boxes are in close stage notified in the “YELLOW” color. When any of those boxes are clicked the color changes to “CYAN” and text changes to “OPEN”. Then the colors and texts toggle when these 2 different boxes are clicked.
The files used to implement the code below are:
Trap.js
import React from "react";
import ReactDOM from "react-dom";
class Trap extends React.Component {
state = { trapped: false };
componentDidMount() {
const { event } = this.props;
this.ref = ReactDOM.findDOMNode(this);
document.addEventListener(event, this.handleEvent);
}
componentWillUnMount() {
const { event } = this.props;
document.removeEventListener(event, this.handleEvent);
}
handleEvent = (
{
target
}
) => {
const trapped = this.ref.contains(target);
this.setState({ trapped });
};
render() {
const { children } = this.props;
const { trapped } = this.state;
return children(trapped);
}
}
export default Trap;
TrapWithRef.js
import React from "react";
class TrapWithRef extends React.Component {
state = { trapped: false };
componentDidMount() {
const { event } = this.props;
document.addEventListener(event, this.handleEvent);
}
componentWillUnMount() {
const { event } = this.props;
document.removeEventListener(event, this.handleEvent);
}
handleEvent = (
{
target
}
) => {
const trapped = this.ref.contains(target);
this.setState({ trapped });
};
render() {
const { children } = this.props;
const { trapped } = this.state;
return children(
trapped, ref => (
this.ref = ref
)
);
}
}
export default TrapWithRef;
index.js (of Traps folder)
export { default as Trap } from "./Trap";
export { default as TrapWithRef } from "./TrapWithRef";
index.js
import React from "react";
import ReactDOM from "react-dom";
import { Trap
, TrapWithRef } from "./Traps";
import "./styles.css";
function App() {
return (
<div className="app">
<div>
<h1>Heyoo! Welcome to </h1>
<h4>TRAINING_REGISTRATION</h4>
<Trap event="click">
{trapped => (
<div className={`box ${!trapped && "untrapped"}`}>
<div>{trapped ? "open" : "close"}</div>
</div>
)}
</Trap>
</div>
<div>
<h1>Our Website</h1>
<h4>WEBINAR_REGISTRATION</h4>
<TrapWithRef event="click">
{(trapped, ref) => (
<div ref={ref} className={`box ${!trapped && "untrapped"}`}>
<div>{trapped ? "open" : "close"}</div>
</div>
)}
</TrapWithRef>
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
styles.css
.app {
display: flex;
justify-content: space-around;
}
.box {
cursor: pointer;
transition: all 250ms ease-in-out;
display: flex;
justify-content: center;
align-items: center;
border-bottom-left-radius: 50%;
border-bottom-right-radius: 50%;
width: 150px;
height: 100px;
background-color: #60f0c7;
font-size: 1.4rem;
color: #2e2e2c;
}
.box.untrapped {
background-color: #fff459;
}
Output:
Example #3 – React DOM findDOMNode With RESET Link
The root node of the DOM model is returned once we call the ReactDOM.findDOMNode(this) method in the component class.
The files used to implement the codes below are:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS findDOMNode()</title>
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<style>
#training1 {
border:2px solid #e82a86;
padding: 6px;
margin-top: 21px;
}
</style>
</head>
<body>
<h3>Example of findDOMNode()</h3>
<a href="">Click to Reset</a>
<div id="training1"></div>
<script src="findDOMNode-example.jsx" type="text/babel"></script>
</body>
</html>
index.js
import React from "react";
import ReactDOM from "react-dom";
class Trainings extends React.Component {
doFind() {
var node = ReactDOM.findDOMNode(this);
node.style.border = "5px solid yellow";
}
render() {
return (
<ul>
<li>React Training</li>
<li>DataScience Training</li>
<li>Data Analytics Training</li>
<li>
<button onClick={() => this.doFind()}>Click Here</button>
</li>
</ul>
);
}
}
ReactDOM.render(<Trainings />, document.getElementById("training1"));
Output:
Conclusion
On the basis of this article, we understood the concept of the React Dom findDOMNode method. We went through its working and the different examples which will help you to understand its application. I hope this article would have made the concept simpler and informative.
Recommended Articles
This is a guide to React Dom Finddomnode. Here we discuss the Working of React Dom Finddomnode along with the examples. You may also have a look at the following articles to learn more –