Async Image Load with React and Redux
Plenty of ways to do it.
One of which is to write your own component, where, a newly loaded image prompts a redraw in componentDidMount
. Here's the full source code of a lazy image that you can use in your own project:
export default class LazyImage extends React.Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
error: false
};
}
componentDidMount() {
const img = new Image();
img.onload = () => {
this.setState({
loaded: true
});
};
img.onerror = () => {
this.setState({
error: true
});
};
img.src = this.props.src;
}
render() {
if (this.state.error) {
return <img
className={this.props.className}
style={this.props.style}
src={this.props.unloadedSrc}
alt={this.props.alt} />
} else if (!this.state.loaded) {
return <img
className={this.props.className}
style={this.props.style}
src={this.props.unloadedSrc}
alt={this.props.alt} />
}
return <img
className={this.props.className}
style={this.props.style}
src={this.props.src}
alt={this.props.alt} />
}
}
Which you would then use like so:
<LazyImage unloadedSrc={unloadedSrc} src={src} />
And then, you have the option of using a plethora of components that you can find just by googling the terms:
- "image load react"
- "react image lazy load"
Or any similar search term variety, thereof. My favourite component is react-imageloader
.
I hope this helps.