Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-redux get width of component's parent div

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?

like image 714
Christos Avatar asked Sep 02 '16 06:09

Christos


People also ask

How do you find the width of a parent div React?

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.

How do you find the height and width of a div in React?

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.

How do I get the useRef height of an element?

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.


1 Answers

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

like image 104
Joy Avatar answered Oct 13 '22 01:10

Joy