A implentation of findDOMNode
that should work in all React versions
Because in React v19 removed it from react-dom
and it has many use cases + it may be hard to stop using it.
React v19 wants ref's to be used but ref's can be a hassle / add a lot more code that isn't needed.
This should also work on every react version for cross compat libs.
Without using refs this wouldn't be possible in React 19+
import { Children, Component } from "react";
import { findDOMNode } from "react-find-dom-node";
class WrapperComponent extends Component {
componentDidMount() {
findDOMNode(this).style.color = "red";
}
render() {
return Children.only(this.props.children);
}
}
function ChildComponent() {
return (
<div>Hello World</div>
);
}
// React Code
<div>
<ChildComponent />
<WrapperComponent>
<ChildComponent />
</WrapperComponent>
</div>
// HTML Output
<div>
<div>Hello World</div>
<div style="color: red;">Hello World</div>
</div>
Heres a proper react 19 implementation
import { Children, Component, useRef } from "react";
class WrapperComponent extends Component {
componentDidMount() {
this.props.ref.style.color = "red";
}
render() {
return Children.only(this.props.children);
}
}
function ChildComponent({nodeRef}) {
return (
<div ref={nodeRef}>Hello World</div>
);
}
// React Code
const ref = useRef(null);
<div>
<ChildComponent />
<WrapperComponent ref={ref}>
<ChildComponent nodeRef={ref} />
</WrapperComponent>
</div>
// HTML Output
<div>
<div>Hello World</div>
<div style="color: red;">Hello World</div>
</div>