7

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

1 Answer 1

14

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)} />;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, thanks a lot. I had the hope that there was a way to use the alt attribute. But this solution works fine. In my example I had to add {this.state.didLoad && <Label bsStyle="primary" className={${styles.label} ${styles.price}}>{PREIS} &#8364;</Label> }, since the label did the trouble. Manipulating the styles didn't work that well, since I use react-bootrstrap and it would overwrite the complete style of the image component.
Oops, didn't notice this was for React & not React Native. Anyway, thanks for the hooks answer. For React Native, I had to change visibility: 'hidden' to opacity: 0. I also had to add a key={didLoad} prop to the <Image>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.