Get DOM Element of Current Component with React-DOM: NULL returned

Asked By: Anonymous

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 
   }, []); 

}

Solution

Answered By: Anonymous

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} />;
}
techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno