vicg
vicg

Reputation: 1368

How to animate child prop changes in react?

I'm trying to create a component that takes a child prop and when this child prop changes I'd like the old component that was the child prop to animate out of screen and the new component to animate in. I attempted to do this using react-spring using the code below, you can run it here https://codesandbox.io/s/react-spring-issue-898-forked-ril7mc?file=/src/App.js.

What am I missing here? Shouldn't the component animate left when it unmounts and animate in from the right when it mounts?

/** @jsx jsx */
import { useState } from "react";
import { useTransition, animated } from "react-spring";
import { jsx } from "@emotion/core";

function FadeTransition({ children, onClick }) {
  const [toggle, setToggle] = useState(true);
  const transition = useTransition(toggle, {
    from: {
      opacity: 0,
      transform: "translateX(100%)"
    },
    enter: {
      opacity: 1,
      transform: "translateX(0)"
    },
    leave: { transform: "translateX(-100%)" }
  });

  return (
    <div>
      {transition(
        (props, item) =>
          item && <animated.div style={props}>{children}</animated.div>
      )}
      <button
        onClick={() => {
          setToggle(!toggle);
          onClick();
        }}
        style={{ marginTop: "2rem" }}
      >
        Change
      </button>
    </div>
  );
}
export default function App() {
  const [currentComponent, setCurrentComponent] = useState(0);
  let components = [<div>Thing 1</div>, <div>Thing 2</div>];
  const onClick = () => {
    setCurrentComponent((currentComponent + 1) % 2);
  };
  return (
    <div style={{ paddingTop: "2rem" }}>
      <FadeTransition onClick={onClick}>
        {components[currentComponent]}
      </FadeTransition>
    </div>
  );
}

Upvotes: 1

Views: 993

Answers (1)

Prashant Shah
Prashant Shah

Reputation: 246

I didn't use rect-sprint as much,There is issue with toggle state so when thing 1 is rendered animation component (FadeTransition) is rendered with setting up toggle state to true.

Now when you click on change button we are setting up the toggle button to opposite of current state which will be false this time and without unmounting animation component (FadeTransition) it will update dom and so the item which is thing 2.

As we are passing toggle in useTransition and if it's values will be false then animation will not be performed.

So I have updated snippet of yours, Here is the working example codesandbox

Upvotes: 1

Related Questions