Search code examples
reactjsjsxreact-spring

Ignore initial Transition for first mount React-Spring


I have a react component which needs a transition for for in and out. But on the first mount it should not use an entry animation. I use a simple fade in fade out. the initial keyword should deactivate the initial transition for the first mount. But it does not work. The following transitions work as aspected.

I tried to find a solution but most of the topics were outdated or did not work for me. Maybe I am missunderstanding something since I am pretty new to React & React-Spring.

<Transition
    native
    items={this.state.showComponent}
    initial={null}
    from={{opacity:0}}
    enter={{opacity:1}}
    leave={{opacity:0}}
>
{show => show && (props =>
    <animated.div style={props}>
        //Component content                   
    </animated.div>
)}
</Transition>

Solution

  • If you do not want to see the initail transition you should introduce a flag for it. And based on the flag you can change the from property of the transition. The flag could be either a class variable or a state variable. For example:

    class MyComponent extends React.Component {
    
    initialised = false;
    
    componentDidMount {
      initialised = true;
    }
    
    ...
    
    <Transition
        native
        items={this.state.showComponent}
        initial={null}
        from={{opacity: this.initialised ? 0 : 1}}
        enter={{opacity:1}}
        leave={{opacity:0}}
    >
    {show => show && (props =>
        <animated.div style={props}>
            //Component content                   
        </animated.div>
    )}
    </Transition>