0

I need to set component dimensions depending on parent element. Is it possible to get width and height of parent by ref from virtualDOM before it renders?

Parent

export default class App extends React.Component {
  render() {

    return (
      <div>
        <div className={'avocado-container'} ref={(container) => { this.container = container; }}>
          <Resizer parent={this} scrollAxis={'y'}>
          </Resizer>
        </div>
      </div>
    );
  }
}

I need to get the dimensions in constructor of child.

Is is possible with something like this.refs.container.offsetWidth ?

1 Answers1

0

No. Layout dimensions are calculated by the browser, not the Virtual DOM. Either set the dimensions by hand, or use CSS to make your child component fill width and height. You can also read the width and height from the rendered component in componentDidMount and call setState in there, which isn't ideal and will cause a second render, but sometimes needs to be done.

Andy Ray
  • 30,372
  • 14
  • 101
  • 138
  • will such component be testable? – uladzimir Feb 12 '17 at 17:05
  • if you need to test the reading of element dimensions flow in didMount, you can use tools like jsdom to supply the neccessary environment. if you don't want to test it, you can do an `if` statement in the didMount to check for the existance of certain objects, like `global.window` – Andy Ray Feb 12 '17 at 17:07
  • don't get me wrong, but jsdom hasn't support of getting real width and height of html element, so it will be hard to test without real browser environment asaik – uladzimir Feb 12 '17 at 17:11