Reputation: 101
This is part of the component :
import MyComp from '../../lib/MyComp'
const Data = ( { data } ) => (
<div className="data-box" id="data-box">
<MyComp data={data} />
</div>
)
How do I get the width of the data-box
div inside MyComp container?
Upvotes: 9
Views: 18163
Reputation: 9550
Check this working demo: JSFiddle:
var Parent = React.createClass({
render: function() {
return <div id="parent">Hello Parent<Child></Child></div>;
}
});
var Child = React.createClass({
componentDidMount: function() {
alert('Parent width: ' + this.refs.child.parentNode.clientWidth);
},
render: function() {
return <div ref="child">Hello Child</div>;
}
});
Stating ref="child"
will make the element accessable by the component itself, through this.refs.child
. It is the vallina node instance. Using this.refs.child.parentNode.clientWidth
will return the parent's width. Or, use this.refs.child.parentNode.getBoundingClientRect()
.
Reference: React refs
Upvotes: 13
Reputation: 609
what should work is something like this MyComp could look like this
render() {
return <div ref="node"></div>
}
with this.refs.node
you get the current dom element and with
this.res.node.parentNode
you should get the parentNode
Upvotes: 0
Reputation: 5136
You need to use react refs.
on your MyComp class:
class MyComp extends React.Component {
//All your PropTypes and functions...
//New function
newFunction () {
console.log(this.refs.refName);
//This will give you the Data component. There you can call methods to calculate width, or whatever you need to do with that component
}
//Your render function
render() {
return <div ...whatever you have... ref="refName">
}
}
You can check react documentation
Upvotes: 1