2

I have a grid of components with 3 per row.

They are divs which represent a product and have inner components such as price and description. These products sometimes have longer titles which push the other components downward.

This is fine, but when it happens I want the titles for the other components in the same row to have a height the same, so that the next components (price, rating) are vertically aligned. So the price for each product in a row will be the same.

Then, I want to make the height of the row the max height of the three elements in the row.

Is there a good way I can manipulate the height of elements dynamically which will work with react?

2 Answers 2

4

I would inject a function in all child components which is called after the child component is rendered.

Example:

var Product = React.createClass({

  componentDidMount: function() {
    var height = 200; // calculate height of rendered component here!
    // set height only one time
    if (this.props.findHeight) {
        this.props.setHeight(height);
    }
  },

  render: function() {
    return <div style={{height:this.props.height,backgroundColor:'green'}}>
            Product
        </div>;
  }
});

var Main = React.createClass({
  getInitialState: function() {
    return {
      maxHeight:0,
      findHeight: true
    }
  },

  componentDidMount: function() {
    this.setState({
        maxHeight: this.state.maxHeight,
        findHeight: false
    });
  },

  setMaxHeight: function(maxHeight) {
    if (maxHeight > this.state.maxHeight) {
      this.setState({maxHeight: maxHeight})
    }
  },

  render: function() {
    return (<div>
             <Product setHeight={this.setMaxHeight} height={this.state.maxHeight} findHeight={this.state.findHeight} />
           </div>);
  }
});

The logic how to calculate the actual height of a component is a different question. You can solve it e.g. with jQuery (How to get height of <div> in px dimension). Unfortunately I can not answer the question for vanilla js, but I am sure that you find the answer very fast when you ask google :-)

Greetings

Sign up to request clarification or add additional context in comments.

Comments

0

By extending the answer provided by CapCa, you can get the actual height of the component by Element.getBoundingClientRect().

let domRect = element.getBoundingClientRect();

You can also target the top element of your targeted react component by using React Ref. Your code could be like this,

let domRect = this.TargetedElementRef.getBoundingClientRect(),
    elementHeight = domRect.height,
    elementWidth = domRect.width;   // you can get the width also

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.