Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass DOM Element as a prop in React

So I have a component that needs a DOM element passed in as a prop. I'm trying to use it in another component like so:

    <div>
        <div className="myPropDiv" ref="myPropDiv">...</div>
        <CustomComponent view={ this.refs.myPropDiv } />
    </div>

But that doesn't work because (I suspect) the DOM hasn't been rendered at the point I'm calling this.refs.myPropDiv. How would I accomplish something like this?

like image 282
andy Avatar asked Jan 22 '16 14:01

andy


People also ask

How do you pass an element as a prop in React?

You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop.

Can we pass component as a prop?

In the previous example, it was only a string variable. But props can be any JavaScript data type from integers over objects to arrays. Via props you can even pass React components as well, which you will learn about later.

How do you access the DOM element 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.


2 Answers

In most situations this is not a good idea, and at least it doesn't look like it is following the React way.

Firstly by getting that div via refs, you don't get DOM element but rather backing instance of that div. You can get the DOM element like toomanyredirects is suggesting.

What are you trying to achieve anyway? One advantage of React is you don't have to mess with original DOM, but play with the virtual one. If you want to just display that div inside your component, than pass it like this.

<CustomComponent> <div className="myPropDiv" ref="myPropDiv">...</div> </CustomComponent>

Then, you can access that div inside your CustomComponent as props.children.

like image 61
Skocdopole Avatar answered Sep 17 '22 00:09

Skocdopole


You can't directly access the DOM, but you can access the DOM element for a React component with ReactDOM.findDOMNode(component), so to use it inside a componentDidMount call you'd use:

var MyComponent = React.createComponent({
  ...
  componentDidMount: function() {
    var component = this,
      node = ReactDOM.findDOMNode(component);
  }
  ...
});

Then if you are looking for a child node of that parent DOM node, you can traverse the DOM normally from that node, for example:

var childNode = node.querySelectorAll('.child-node-class')[0];

Then you can pass it to wherever you originally wanted it.

like image 26
toomanyredirects Avatar answered Sep 17 '22 00:09

toomanyredirects