learningtech
learningtech

Reputation: 33695

access root element of react component

If I have the following in the render() function of my react component

return <div ref="myId"></div>;

I know I can access the div element in my react code with this.refs.myId. But if the ref attribute were not defined in the div element, is there another way for me get a handle on the div element since it is a root element of the component?

Upvotes: 28

Views: 32352

Answers (2)

Miguel Coder
Miguel Coder

Reputation: 1950

The answer above has been deprecated in favor of using the forwardRef attribute. Now there should be a mechanism (meaning you have to create it) for forwarding the root node to the parent using the forwardRef function as shown below

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

https://reactjs.org/docs/forwarding-refs.html

Upvotes: 7

Rose Robertson
Rose Robertson

Reputation: 1256

You can get the root element for a component using ReactDOM (https://www.npmjs.com/package/react-dom) ReactDOM.findDOMNode(this)

Upvotes: 26

Related Questions