Restart animation on state/props change in react-motion
Asked Answered
S

1

5

I am trying to animate breadcrumbs using react-motion from x: -20 to x: 0.

Folder > SubFolder > Child

The issue is, the breadcrumbs animate perfectly on the first render. Subsequently when the props or even state changes, the animations are not updated. This seems to be a known bug.

My question is, how do I "restart" animation on state/prop changes?

const getDefaultStyles = crumbs => {
  const defaultStyles = crumbs.map(() => ({x: -20}))
  console.log(defaultStyles)
  return defaultStyles
}

const getStyles = previousInterpolatedStyles => {
  return previousInterpolatedStyles.map((_, i) => {
    return i === 0 ? {x: spring(0)} : {x: spring(previousInterpolatedStyles[i-1].x)}
  })
}

const Breadcrumb = ({ crumbs }) => (
  <div className='breadcrumb-container'>

      <StaggeredMotion
        defaultStyles={getDefaultStyles(crumbs)}
        styles={getStyles}>
        {
          interpolatedStyles =>
            <div className='breadcrumb-list'>
              {
                interpolatedStyles.map(({x}, i) =>
                  <div className='breadcrumb' key={i} style={{
                      WebkitTransform: `translate3d(${x}px, 0, 0)`,
                      transform: `translate3d(${x}px, 0, 0)`
                    }}>
                    <a href='#'>Title</a>                    
                  </div>
                )
              }
            </div>

        }
      </StaggeredMotion>

  </div>
)
Sharpen answered 17/12, 2016 at 4:30 Comment(0)
S
10

Going through the react-motion, I've found a fix by setting a unique key prop in Motion, StaggeredMotion causes it to re-render on state change.

Refer this issue on the official repo.

For my case I solved it by setting the key prop to the length of the breadcrumb list.

<StaggeredMotion
      key={this.props.crumbs.length}
      ...>
    ...
</StaggeredMotion>
Sharpen answered 20/12, 2016 at 2:47 Comment(1)
This also solved my issue for re-animating a flash message. First render was always fine but upon rerender, animation did not get reset. Setting key prop to Date.now() solved my issue since I always want to re-animate when a new flash msg appears.Uel

© 2022 - 2024 — McMap. All rights reserved.