Get the exact width and height of the images in the reaction.

I am new to react. I have an array of images loaded by a file downloader plugin . and I display them like this:

images.map((img, index) => <img src={img}>

How can I get the width and height attributes of each image? I know how I can set attributes, but I do not know the height and width of the images, as they are in the array.

+2
source share
3 answers

You could learn something like image-size-loader. file-loaderdoes not offer the behavior you are looking for.

+4
source

You can receive data using the onLoad attribute.

class ImgLoader extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: false,
    };
  }

  onImgLoad = ({ target: img }) => {
    this.setState({
      width: img.width,
      height: img.height,
    });
  };

  onImgError = e => {
    e.target.src = '/path/no-picture.jpg';
    this.setState({
      error: true,
    });
  };

  render() {
    const { image, alt } = this.props;
    const { width, height, error } = this.state;
    console.log(width, height, error);
    return <img onLoad={this.onImgLoad} src={image} alt={alt} onError={this.onImgError} />;
  }
}
0
source

, , . , .

<img style={{width: '50px', height: '50px'}} src={img} />

CSS

import './MyCSSFileName'

<img className="fixed_img" src={img} />

// in your .css file
.fixed_img {
  width: 50px;
  height: 50px;
}
-1
source

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


All Articles