0

I was following this article that says you can get the DOM element of the current component as ReactDOM.findDOMNode(this).

But when I try this I get a NULL result in the node var:

export default function Component(props) {

    // Initialization
   useEffect(() => {
    const node = ReactDOM.findDOMNode(this);
    console.log(node); // NULL 
   }, []); 

}
gene b.
  • 10,512
  • 21
  • 115
  • 227
  • It doesn't work in function component since `this` not referring to component's instance like in class components. In function component you attaching `useRef` to the root component. – Dennis Vash May 20 '21 at 20:48
  • It even mentioned in docs "findDOMNode cannot be used on function components.", https://reactjs.org/docs/react-dom.html#finddomnode – Dennis Vash May 20 '21 at 20:50
  • So what's the correct way to get the DOM element of the Component itself in a functional component? any examples? – gene b. May 20 '21 at 20:54

1 Answers1

2

findDOMNode won't work in function component, aside from what is written in the docs ("findDOMNode cannot be used on function components."), it has to do with the fact that function components don't have instances like classes, read carefully related question.

In function component, you get the current DOM element by attaching a ref to the root node:

export default function Component(props) {
  const nodeRef = useRef();

  useEffect(() => {
    console.log(nodeRef.current);
  }, []);

  // Root Node
  return <input ref={nodeRef} />;
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118