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} €</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
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)} />;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With