3

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?

Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70
  • If `isExpanded` is falsy it is returned as the `children` props to the `Transition` component which seems to expect a render prop, which you correctly return in t he case `isExpanded` is truthy. You can refactor this using a ternary operator and returning some kind of noop function when `isExpanded` is falsy. – adz5A Nov 09 '18 at 15:35
  • @adz5A when isExpanded is 'true' error is ' TypeError: child is not a function', and if its 'false' - ' TypeError: _children is not a function' – Volodymyr Humeniuk Nov 09 '18 at 15:40
  • This is because the signature for the `children` in your snippet is not correct. It is a function which returns a function: `item => props => reactElement`. See http://react-spring.surge.sh/transition . Your example lacks the `items` props and a correct signature for the `children` props. – adz5A Nov 09 '18 at 15:53

1 Answers1

5

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

Gabriel Petersson
  • 8,434
  • 4
  • 32
  • 41
hpalu
  • 1,357
  • 7
  • 12