Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle image loading in React

I'm using this code to load images

{Image} from 'react-bootstrap';
<Image src={res.imgUrl} className={styles.image} onError={(e)=>{e.target.src="/defaultImage.png"}} responsive thumbnail />
<Label bsStyle="primary" className={styles.price}}>{Price} &#8364;</Label>

Here is the css code for the label

.price {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 0.95em;
    }

It works fine. But during loading the "Label"-Element shows up not nicely, since there is no image yet that has been loaded and it have not enough place to show up.

Is there a nice solution for this?

Thanks!

PS: It looks like this during loading

enter image description here

like image 959
MichaelRazum Avatar asked Dec 23 '22 16:12

MichaelRazum


1 Answers

A simple solution is to leverage the onLoad event, and a didLoad flag to delay rendering the image until it is fully loaded.

class Example extends Component {

    constructor(props) {
        super(props);

        this.state = {
            didLoad: false
        }
    }

    onLoad = () => {
        this.setState({
            didLoad: true
        })
    }


    render() {
        const style = this.state.didLoad ? {} : {visibility: 'hidden'}
        return (
            <img style={style} src={this.props.src} onLoad={this.onLoad} />
        )
    }
}

As requested, an example using hooks:

function VisImgExample({src}) {
  const [didLoad, setLoad] = React.useState(false);

  const style = didLoad ? {} : {visibility: 'hidden'};

  return <img style={style} src={src} onLoad={() => setLoad(true)} />;
}
like image 139
enjoylife Avatar answered Dec 31 '22 01:12

enjoylife