0

I'm using react-spring with the render-props API to set a background-size CSS property. The change is triggered whenever the background image changes. The thing is: the background image does not always load fast enough for the background size to change flawlessly.

Is there a way to delay the Spring until the background image is loaded, or do I have to preload all my background images beforehand?

There is a lot of background images that can be set to my object and they are quite large in size, so preloading them might take a lot of space in memory so it's not optimal in my case.

Here is my code:

<Spring native
    from={{backgroundSize: "105%", backgroundImage: streamRectangleBackground}}
    to={{backgroundSize: "101%", backgroundImage: streamRectangleBackground}}
    reset={this.shouldResetAnimation(streamRectangleBackground)}>
    {props =>
        <animated.div className={"streamRectangle"} style={props}>
            <Timer timerSetup={this.state.timerSetup}/>
        </animated.div>
    }
</Spring>

Thanks

Piorrro33
  • 19
  • 8

1 Answers1

2

I have an idea you might use here. For img components there is a onLoad event handler. If you display an image with the same src hidden somewhere on the page. Then you can set a state when the image is finally loaded.

Then use this state to change the to property of the Spring component. Something like this:

<img
  style={{display: 'none'}}
  src={streamRectangleBackground}
  onLoad={() => this.setState({loaded: true})}
/>

<Spring native
    from={{backgroundSize: "105%", backgroundImage: streamRectangleBackground}}
    to={{backgroundSize: ${this.state.loaded ? "101%" : "105%"}}}
    reset={this.shouldResetAnimation(streamRectangleBackground)}>
    {props =>
        <animated.div className={"streamRectangle"} style={props}>
            <Timer timerSetup={this.state.timerSetup}/>
        </animated.div>
    }
</Spring>

Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36