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?
To get the parent height and width in React: Set the ref prop on the element. In the useEffect hook, update the state variables for the height and width. Use the offsetHeight and offsetWidth properties to get the height and width of the element.
To calculate the width and height of an element, we can use the useRef hook: const myRef = useRef(); // Width const width = myRef. current. clientWidth; // Height const height = myRef.
To get the height of an element with React, we can assign a ref to the element we want to get the height for. Then we can use the clientHeight property to get the height. We call the useRef hook and assign the returned ref to elementRef . Then we set elementRef as the value of the ref prop of the div.
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
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