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>
)
sanchit
  • 2,328
  • 2
  • 18
  • 22

1 Answers1

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>
sanchit
  • 2,328
  • 2
  • 18
  • 22
  • 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. – SidOfc Oct 11 '17 at 10:21