Search code examples
reactjscss-transitionstransition

ReactJS - Fade between 2 different components


I am trying to figure out how to fade between 2 different components with a nice easy 1 second transition. I have played around with SwitchTransition and CSSTransition and TransitionGroup and nothing seems to work quite right for me. It looks like SwitchTransition is what I am looking for but the only examples I can find they are just swapping out text and not whole components.

So here is the code for my two components which are shown conditionally based on state variables. Each component has a button that will swap the state variable values so it will currently swap between the two, but it doesn't look real pretty.

<div className="login col-md-6 mt-5 mx-auto">
  {showLogin && (
    <LoginForm
      onLoginSubmit={onLoginSubmit}
      email={email}
      setEmail={setEmail}
      password={password}
      setPassword={setPassword}
      showPasswordReset={showPasswordReset}
    />
  )}
  {showForgotPassword && (
    <ForgotPasswordForm
      onPasswordResetSubmit={onPasswordResetSubmit}
      setShowForgotPassword={setShowForgotPassword}
    />
  )}
</div>

Solution

  • You can use react-spring to animate your components, first

    import { animated, useTransition } from "react-spring";
    

    then inside your component

    const [showLogin, set] = useState(false);
    
    const toggle = () => {
        set(!showLogin);
    };
    
    const transitions = useTransition(showLogin, null, {
            from: { position: "absolute", opacity: 0 },
            enter: { opacity: 1 },
            leave: { opacity: 0 }
          });
    

    and then you will render your components, make sure to replace div with animated.div

    <div className="login col-md-6 mt-5 mx-auto">
        {transitions.map(({ item, key, props }) =>
            item ? (
                <LoginForm //animated.div
                    onLoginSubmit={onLoginSubmit}
                    email={email}
                    setEmail={setEmail}
                    password={password}
                    setPassword={setPassword}
                    showPasswordReset={showPasswordReset}
                />
            ) : (
                <ForgotPasswordForm //animated.div
                    onPasswordResetSubmit={onPasswordResetSubmit}
                    setShowForgotPassword={toggle}
                />
            )
        )}
    </div>
    

    I made a simple example, you can check it out here