2

Faulty Behavior: On new adding new item, 'entering' is activated for all them items and when deleting item, neither 'exit' nor 'exiting' runs for deleting or any other items.

Animations are working fine when transition children are directly inside TransitionGroup component. But logic of my code is such that i have to run it inside another component. The animations does not work like before.

Is there anything else we must do other than spreading the injected props into the nested Transition component?

Works like this

<TransitionGroup>
  {fruits.map(({id, name}) => (<Transition key={id} timeout={1000}>
    {(state) => {
      //state logic
      return (<h3>{name}</h3>);
    }}
  </Transition>)}
</TransitionGroup>

Doesnt work like this

const ChildrenComp = (props) => {
  return fruits.map(({id, name} => (<Transition {...props} key={id} timeout={1000}>
    {(state) => {
      //state logic
      return (<h3>{name}</h3>);
    }}
  </Transition>));
};

<TransitionGroup>
  <ChildrenComp /> // inside another component
</TransitionGroup>

Entire Code

const Animate = () => {
  const [fruits, setFruits] = React.useState(items); 
  
  const handleAdd = () => {
    setFruits((prev) => setFruits([
      ...prev,
      { id: uuid(), name: `fruit-${uuid().slice(0,4)}` },
    ]));
  };

  const handleDelete = () => {
    setFruits((prev) => setFruits(prev.slice(0, prev.length - 1)));
  };

  const GroupChildren = (props) => {
    return fruits.map(({id, name}) => {
      return (
        <div key={id}>
          <Transition {...props} key={id} timeout={TIMEOUT}>
            {(state) => {
              const isExiting = state === 'exiting' || state === 'exited';
              const isEntering = state === 'entering';
              const isEntered = state === 'entered';
  
              const animateClasses = classNames({    
                'animation-exit': isExiting,
                'animation-enter': isEntering,
                'animation-entered': isEntered,
              });                
  
              if (state === 'exiting' || state === 'exited') {
              }
              
              return (
                <h3 className={animateClasses}>{name}</h3>
              );
            }}
          </Transition>
        </div>
      );
    });
  };

  return (
    <div>
      <h1>Animation</h1>
      <TransitionGroup>        
        {fruits && <GroupChildren />}        
      </TransitionGroup>
      <div>
        <button onClick={handleAdd}>add</button>
        <button onClick={handleDelete}>delete</button>
      </div>
    </div>
  );
};

Styles

.animation-enter {
  background-color: green;
}

.animation-exit {
  background-color: red;
}

.animation-entered {
  background-color: #ddd;
}

0 Answers0