Show default item when loading image

I have a component representing a user avatar that loads an image from my API. I want it to display the default avatar (not another image) while loading the avatar.

constructor() { super(); this.state = { loaded: false, }; } render() { if (!this.props.uri || !this.state.loaded) { return ( <DefaultAvatar /> ); } return <Image onLoad={this.onLoad.bind(this)} uri={this.props.uri} />; } onLoad() { this.setState({loaded: true}); } 

The problem is that with this current code, Image will never be displayed, so the state will never change. I can’t find a solution that satisfies the React principles and my requirements (without ghost components to download the image before displaying it).

+5
source share
3 answers

Image.prefetch will let me do what I want, thanks to everyone.

0
source
 class LazyImage extends React.Component{ constructor () { super(this.props) this.state = {loaded: false} } handleLoad () { this.setState({loaded:true}) } componentDidMount () { this.img = new Image() this.img.onload = this.handleLoad.bind(this) this.img.src = this.props.src } render () { return this.state.loaded?<img src={this.props.src}/>:<div>Loading...</div> } } 

You create your own Image element and wait for it to load. Then you render the image. The browser is smart and will select it from the cache this time. Instant render!

See http://jsfiddle.net/4hq3y4ra/3/ for a demonstration.

+3
source

There are several ways to achieve this, however, to keep things simple, you can use the literal condition to switch the default avatar and the actual image.

 constructor() { super(); this.state = { loaded: false, }; } onLoad(dataUri) { if(dataUri !== undefined){ this.setState({loaded: true}); } }, render() { return ( <Image onLoad={this.onLoad} uri={this.state.loaded ? this.props.uri : 'default-avatar'} /> ); } 
+1
source

Source: https://habr.com/ru/post/1242126/


All Articles