Search code examples
javascriptreactjsreact-pose

React pose - animate in from right, exit on left


I am currently playing around with React pose. What I'm trying to do is animate different boxes in from the right, and exit them on the left. However, I can't seem to get the preEnterPose to work the way I want it. It always seems to default to the exit pose.

How can I get the boxes to animate in from the right, and exit on the left? Here is what I am working with https://codesandbox.io/s/react-pose-enterexit-o2qqi?fontsize=14&hidenavigation=1&theme=dark

import React from "react";
import ReactDOM from "react-dom";
import posed, { PoseGroup } from "react-pose";
import "./styles.css";

const Card = posed.div({
  enter: {
    x: 0,
    opacity: 1,
    preEnterPose: {
      x: 50
    },
    delay: 300,
    transition: {
      x: { type: "spring", stiffness: 1000, damping: 15 },
      default: { duration: 300 }
    }
  },
  exit: {
    x: -50,
    opacity: 0,
    transition: { duration: 150 }
  }
});

class Example extends React.Component {
  state = { isVisible: false, index: 0, items: ["1", "2", "3", "4", "5"] };

  componentDidMount() {}

  next = () => {
    if (this.state.index === this.state.items.length - 1) {
      this.setState({
        index: 0
      });
    } else {
      this.setState({
        index: this.state.index + 1
      });
    }
  };

  render() {
    const { index, items } = this.state;

    return (
      <div>
        <PoseGroup>
          {items.map((id, idx) => {
            if (idx === index) {
              return (
                <Card className="card" key={idx}>
                  {id}
                </Card>
              );
            }
            return null;
          })}
        </PoseGroup>
        <button onClick={this.next}>next</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);

Solution

  • First you update your posed.div as the following.

    const Card = posed.div({
      preEnterPose: {
        x: 50,
        opacity: 0,
        transition: { duration: 150 }
      },
      enter: {
        x: 0,
        opacity: 1,
        delay: 300,
        transition: {
          x: { type: "spring", stiffness: 1000, damping: 15 },
          default: { duration: 300 }
        }
      },
      exit: {
        x: -50,
        opacity: 0,
        transition: { duration: 150 }
      }
    });
    

    Then you set your <PoseGroup>'s preEnterPose props to your key of the pose preEnterPose. And it should work. preEnterPose's default props is set to exit. Read it here

    <PoseGroup preEnterPose="preEnterPose">
      {items.map((id, idx) => {
        if (idx === index) {
          return (
            <Card className="card" key={idx}>
              {id}
            </Card>
          );
        }
        return null;
      })}
    </PoseGroup>