Get React.refs DOM node width after rendering and cause re-rendering only if the width value has changed

I am trying to get the width of the ref DOM element and set state to use in the render component. The problem arises because this width changes when the user enters, and when I try to execute setState inside componentDidUpdate , it starts an infinite loop and my browsers bomb.

I created the fiddle here http://jsbin.com/dizomohaso/1/edit?js,output (open the console for some information)

My thinking was:

  • Component mounts, setState: refs.element.clientWidth

  • User enters data, render triggers

  • shouldComponentUpdate returns true only if new.state not equal to old.state . My problem is that I'm not sure where it makes sense to update this state ?

Any help would be greatly appreciated, thanks for reading!

Rave.

+5
source share
1 answer
 var component = React.createClass({ componentDidMount: function() { //Get initial width. Obviously, this will trigger a render, //but nothing will change, look wise. //But, if this is against personal taste then store this property //in a different way //But it'll complicate your determineWidth logic a bit. this.setState({ elWidth: ReactDOM.findDOMNode(this.refs.the_input).getBoundingClientRect().width }) }, determineWidth: function() { var elWidth = ReactDOM.findDOMNode(this.refs.the_input).getBoundingClientRect().width if (this.state.elWidth && this.state.elWidth !== elWidth) { this.setState({ elWidth: elWidth }) } }, render: function() { var styleProp = {} if (this.state.elWidth) { styleProp.style = { width: this.state.elWidth }; } return ( <input ref="the_input" onChange={this.determineWidth} {...styleProp} /> ) } }) 

I like to use .getBoundingClientRect().width , because depending on your browser, the element may have a fractional width, and this width will be returned without rounding.

+16
source

Source: https://habr.com/ru/post/1243351/


All Articles