Fen1kz Fen1kz - 1 year ago 80
Javascript Question

Animate movement of React component from one to another

I'm trying to figure out how to animate moving react component from one to another. For example take very simple, yet interesting card game: you may place any card to a deck, or take top card from the deck.

To make it work, I have 4 classes -

which holds two
<Card Collection>
: "Deck" and "Hand" components. In constructor, they generate CardModel items and render them via
component has special
prop which takes callback function. In my case it's
onCardClick={/*this is equal to <Board>*/ this.transferCard("Hand")}

takes clicked CardModel from state of one component and pushes it to another.

The problem is animation - I want card to fly, preferably through center (optional!) from old place to new. I am able to place the newly created Card in "new place" to the same place as old component, but, since i jsut strated to learn React, I'm not sure where exactly I should start. Wrap in ReactCSSTransitionGroup? pass "animate: from{x,y} to{x,y}" property to

So the full question is what is the most generic, controllable and "react" way to animate this situation?

JSFiddle base question version: https://jsfiddle.net/fen1kz/6qxpzmm6/

JSFiddle first animation prototype version: https://jsfiddle.net/fen1kz/6qxpzmm6/1

I don't like
here. Also the Animation component looks like an abomination for me, I'm not sure this is the good architecture style for React.

Answer Source

The main mistake I did is try to mix render function with animation. No! Render should not contain anything related to animation (preferably not even starter values), while all the animation should happen after render. The only thing that bothers me is that i still should have state of animations in CardCollection just to throw it into creation of Card

Working example: https://jsfiddle.net/fen1kz/6qxpzmm6/4/

      let animation;
      if (this.animations[cardModel.id] != void 0) {
        animation = this.animations[cardModel.id];
        this.animations[cardModel.id] = void 0;
      return <Card 
               ref={cardModel.id} // prolly not needed
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download