V
V
Vanya Huk2018-09-05 17:28:13
React
Vanya Huk, 2018-09-05 17:28:13

How to change background-image only after loading the react image itself?

the element code is:

<div
      className={'photo-item'}
      style={{backgroundImage: 'url(' + this.props.item.preview + ')'}}
    >
                </div>

this.props.item.preview - url of the image that comes from the server.
How can I make the backgroundImage change only after the image is loaded?
but as soon as the url this.props.item.preview
changes for 2-3 seconds, the picture disappears
5b8fe7f392e68105143954.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-09-05
@vanyahuk

This can be done by using new Image()and subscribing to the onloadevent.
Example taken from redux tutorial code

class BigPhoto extends React.Component {
  state = {
    isLoading: false,
  }
  componentDidMount() {
    this.loadImage(this.props.url)
  }
  loadImage = src => {
    this.setState({ isLoading: true })

    let img = new Image()
    img.onload = () => {
      this.setState({ isLoading: false })
    }

    img.src = src
  }
  render() {
    const { isLoading } = this.state
    const { url } = this.props
    return isLoading ? <p>Загружаю...</p> : <img src={url} alt="big vk" />
  }
}

The main thing to remember is that the image loading starts only when the src attribute is set to it. The onload handler function must be defined in advance! In this approach, we use the native functionality of the browser and js, this is not only suitable for react

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question