andy
andy

Reputation: 2399

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?

Upvotes: 10

Views: 11703

Answers (2)

Daniel Macak
Daniel Macak

Reputation: 17063

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.

Upvotes: 3

toomanyredirects
toomanyredirects

Reputation: 2002

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.

Upvotes: 1

Related Questions