reactjsjsxreact-spring

react-spring single-component mount/unmount reveals


i'm trying to create animation when component mount/unmount with React-spring:

    import { Transition, animated } from 'react-spring'
    ...

    export class CompName extends PureComponent<CompNamePropsType> {
      static defaultProps = {
        isExpanded: false,
      }

      render() {
        const {
          isExpanded,
          ...props
        } = this.props

    return (
      <section className={styles.block} {...props}>
        <Transition
          from={{ opacity: 0 }}
          enter={{ opacity: 1 }}
          leave={{ opacity: 0 }}>
        {isExpanded && (style => (
           <animated.div style={{ ...style, background: "orange" }}>
             <AnotherComp />
           </animated.div>
        ))}
       </Transition>
      </section>
    )
  }
}

But this is just does not work and i got an error children is not a function. What i did wrong, and how can i create animation on component mount/unmount with react-spring wrapper?


Solution

  • The correct way is:

    <Transition items={isExpanded} native from enter leave>
      {isExpanded => isExpanded && (props => <animated.div style={props} />)}
    </Transition>
    

    Items in, can be a single item like in your case, then work against the item that comes out. Reason for that is that transition will retain it, even when the actual state changes, it can still safely transition an element out on the "old" state.

    The api is explained here: react-spring.io/docs/props/transition