React.JS calculating img width in virtual DOM

I am trying to find the width <img>to center it using JavaScript.

Trying to calculate the width of this reaction .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} />
    );
  }
});
+4
source share
2 answers

You can use the image onLoadto make sure it is 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>
Run codeHide result
+10
source

I wrote a React library that provides a size object (with width and height details) for your components.

You can use it like this for your use case:

var SizeMe = require('react-sizeme');

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

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

      console.log(imgEl.offsetWidth);
  },
  render: function () {
    // height and width via props!!
    var width = this.props.width;
    var height = this.props.height;

    return (
      <img ref="imgSize" src={this.props.imageURL} />
    );
  }
});

// Wrap your component with the SizeMe HOC!
module.exports = SizeMe()(Player);

Demo: https://react-sizeme-example-esbefmsitg.now.sh/

Github: https://github.com/ctrlplusb/react-sizeme

0

All Articles