Search code examples
javascriptreactjsreact-motion

On react-motion, how to reset an animation?


In a certain UI a person can update an image, whenever they upload a new image I want the previous one to fade into the new one. The problem is that the animation runs only for the first change:

return(
  <div>
   <Motion defaultStyle={{opacity: 1}} style={{opacity: spring(0)}}>
     { interpolatedStyle => <img style={interpolatedStyle} src={this.previousSrc/> }
   </Motion>
   <img src={this.props.src} />
  </div>
)

I have a component with two <img> inside it, one to display the previous image and another one to display the next. I'm using <Motion> and spring to change the opacity of the old image, the problem is that the animation only runs once, the second time the user updates the image the old image is always invisible already.

How do I reset the animation for every render?


Solution

  • You should use TransitionMotion as it says in the doc: The TransitionMotion component animates components as they mount and unmount. The premise is similar to React Transition Group, but the approach is completely different.

    So for it to work just replace Motion with TransitionMotion & add a unique key attribute.

    <img style={interpolatedStyle} src={this.previousSrc} key={someUniqueValue} />
    

    I feel that will solve the issue.