I have created a react application, which contains posts (with image or text). I have to make sure, that the images are loaded as soon the get displayed, to avoid 'jumping' of the images. I have found a javascript package imagesloaded desandro which detects when images have been loaded.
// Container.js
render() {
let item;
// Array of all items
let items = this.props.items;
if (this.props.items) {
// Map through the items
item = items.map(item => {
// Item with only text
if (item.imageUrl === undefined && item.text) {
return (
// Item without image (only Text)
<TextItem
item={item}
styles={this.props.styles}
/>
);
// Item without text (only image)
} else if (item.imageUrl && item.text === undefined) {
return (
<ImageItem
post={post}
styles={this.props.styles}
/>
);
}
});
}
return <div className="item-container">{item}</div>;
}
But when I call the function to check if the images were loaded, the images were not found, because the aren't rendered yet and I get the error "Bad element for imagesLoaded null". Is it possible to get the node of the items before they get rendered?
// Call function to check if the images were loaded
componentDidMount(){
const container = document.querySelector('.container');
const imgLoad = imagesLoaded(container);
imgLoad.on( 'progress', function( instance, image ) {
let result = image.isLoaded ? 'loaded' : 'broken';
console.log( 'image is ' + result + ' for ' + image.img.src );
});
}
Aucun commentaire:
Enregistrer un commentaire