Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Board.transferCard 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 <CardCollection>?

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 <this.state.animations.map... here. Also the Animation component looks like an abomination for me, I'm not sure this is the good architecture style for React.

like image 720
Fen1kz Avatar asked Jul 22 '16 12:07

Fen1kz


People also ask

How do I move a prop from one component to another?

Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop.


1 Answers

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 
               cardModel={cardModel} 
               onCardClick={onCardClick}
               animation={animation}
               position={this.getCardPosition(i)}
               index={i}
               key={cardModel.id}
               ref={cardModel.id} // prolly not needed
               />
like image 183
Fen1kz Avatar answered Oct 09 '22 01:10

Fen1kz