Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access root element of react component

Tags:

reactjs

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?

like image 593
John Avatar asked Oct 30 '16 02:10

John


People also ask

How do I use root in React?

The root can be used to render a React element into the DOM with render : const root = createRoot(container); root.render(element); createRoot accepts two options: onRecoverableError : optional callback called when React automatically recovers from errors.

What is root element React?

The root node is the HTML element where you want to display the result. It is like a container for content managed by React.

How do you access elements in React?

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.

Can I use document getElementById in React?

The equivalent of the document. getElementById() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .


2 Answers

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

like image 121
Rose Robertson Avatar answered Oct 21 '22 01:10

Rose Robertson


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

like image 22
Miguel Coder Avatar answered Oct 21 '22 02:10

Miguel Coder