Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.JS calculating img width in virtual DOM

I'm trying to find the width of an <img> to center it via JavaScript.

Trying to calculate the width of this react.js DOM node returns 0.

var Player = React.createClass({
  componentDidMount:function(){

      var imgEl = this.refs.imgSize.getDOMNode();

      console.log(imgEl.offsetWidth);
  },
  render: function () {
    return (
      <img ref="imgSize" src={this.props.imageURL} />
    );
  }
});
like image 681
Alec Sibilia Avatar asked Dec 19 '22 06:12

Alec Sibilia


1 Answers

You could use the image's onLoad event to make sure it's loaded before you try this:

<script src="http://fb.me/react-0.12.2.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
<script type="text/jsx;harmony=true">void function() { "use strict";

var Player = React.createClass({
  _onLoad(e) {
    console.log(e.target.offsetWidth)
  },
  render() {
    return <img src={this.props.imageURL} onLoad={this._onLoad}/>
  }
})

React.render(<Player imageURL="http://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg"/>, document.body)

}()</script>
like image 98
Jonny Buchanan Avatar answered Dec 31 '22 02:12

Jonny Buchanan