2K01B5 2K01B5 -4 years ago 104
CSS Question

Finding the width of an element when using React?

At which point in a React components life cycle can I get the components css properties which are set in a css file?

I've tried it in the render method and the componentDidMount method and neither assigned the css properties to the component.

export default class HomeArtist extends React.Component {
constructor(props){
super(props);
}
componentDidMount(){
let ImageStore = document.getElementsByClassName('home-artist-display');
console.log("ComponentDidMount: ", ImageStore);
}
render(){
var ImageStyle = {
backgroundImage: "url("+this.props.info.image+")"
};
return (
<div className="home-artist-display" style={ImageStyle}>
<Link to={"artist/" + this.props.info.id}>
<h3 className="home-artist-name">{this.props.info.name}</h3>
</Link>
</div>
)
}
}

Answer Source

I wrote a React library that exposes a size object (with width and height props) to components.

For your use case you could use it like so:

import SizeMe from 'react-sizeme';  // import me!   

class HomeArtist extends React.Component {
  ...
  render(){
      // Size gets passed in as props!
      const { width, height } = this.props.size;

      var ImageStyle = {
          backgroundImage: "url("+this.props.info.image+")"
      };
      return (
          <div className="home-artist-display" style={ImageStyle}>
              <Link to={"artist/" + this.props.info.id}>
                  <h3 className="home-artist-name">{this.props.info.name}</h3>
              </Link>
          </div>
      )
  }
}

// wrap your component export!
export default SizeMe()(HomeArtist);

--

You can find out full details at https://github.com/ctrlplusb/react-sizeme

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download