Jimmy
Jimmy

Reputation: 3860

Getting height of children elements in a React component

Inside a React component, I want to be able to calculate the combined height of each of my child containers, in this case, the three h3 elements, so that I can calculate the exact height of my parent div when animating the transition of its height. I have seen examples of this with basic js as well as using component mounting methods, but how do I get the height of these elements using just JavaScript?

class Div extends React.Component {
  render() {
    return (
      <div>
        <h3>Description One</h3>
        <h3>Description Two</h3>
        <h3>Description Three</h3>
      </div>
    );
  }
}

ReactDOM.render(<Div />, app);
div {
  background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app"></div>

Upvotes: 6

Views: 26279

Answers (1)

Thomas Hennes
Thomas Hennes

Reputation: 9939

In React, to manipulate the DOM, you'll want to use Refs: React Docs - Adding a Ref to a DOM element.

In your example, for your <h3> elements, you'd do something like this:

    <h3 ref={(elem) => this.Line1 = elem}>Description One</h3>
    <h3 ref={(elem) => this.Line2 = elem}>Description Two</h3>
    <h3 ref={(elem) => this.Line3 = elem}>Description Three</h3>

Once you have a Ref to an element, you can use methods & properties of any DOM element on it. For instance, to get its height, you can use Element.clientHeight:

calcHeight() {
  return this.Line1.clientHeight + this.Line2.clientHeight + this.Line3.clientHeight;
}

Working JSFiddle

Upvotes: 10

Related Questions