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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With