Search code examples
reactjsbackground-image

How to force an image to refresh


Here is a small project I'm working through: https://codesandbox.io/embed/rwxookx6po.

I have several divs that have a backgroundImage property. The url I am hitting is this one: https://source.unsplash.com/collection/1163637/480x480

Every time you visit that url, you will get a new random image from the collection. I thought that because the props aren't changing, I could force my component to update, but that didn't seem to solve the problem:

shouldComponentUpdate(nextProps) {
    if (nextProps.image) {
      this.forceUpdate();
      return true;
    }
  }

Given I press a button and pass the same image url prop to my component containing the divs with the background images, how can I get the component to reload, giving my divs a new image background?


Solution

  • You can add a timestamp to your updateImage method, like this:

    updateImage() {
      const width = 480;
      const height = 480;
      const timestamp = Date.now();
      const imageURL = `https://source.unsplash.com/collection/1163637/${width}x${height}?t=${timestamp}`;
      return this.props.updateImage(imageURL, width, height);
    }