react-transition-group icon indicating copy to clipboard operation
react-transition-group copied to clipboard

Delay before animation begins

Open Richardinho opened this issue 8 years ago • 36 comments

In the first example given in the documentation there is a noticeable delay between clicking the button and the animation starting. This delay seems to correspond to the duration of the timeout property. Clearly, one would desire the animation to begin straight away, normally, as well as being able to configure a delay in some cases. It's not so obvious in the example because the timeout isn't very large, but when you set it to a bigger number you begin to see the issue.

In my own experiment I set start and end properties for the respective entering and exit states.

const transitionStyles = {
  entering: { left: 0 },
  entered: { left: '100px' },
};

What then happens is that the start property is immediately set, but that then a delay occurs before the animation kicks in.

I get the desired effect if I set the property to be the same in both states (and set the default to 0), but this doesn't seem right.

const defaultStyles = {
  left: 0,
}
const transitionStyles = {
  entering: { left: '100px' },
  entered: { left: '100px' },
};

Here is the full code for the my experiment when there is an unwanted delay at the start of the animation:

import ReactDOM from 'react-dom';
import React from 'react';
import { Transition } from 'react-transition-group';

const duration = 1600;

const defaultStyle = {
  transition: `left ${duration}ms linear`,
  position: 'absolute',
  top: 200,
  width: '100px',
  height: '100px',
}

const transitionStyles = {
  entering: { left: '0' },
  entered:  { left: '400px'},
};

class Foo extends React.Component {
  constructor () {
    super();
    this.state = {
      in: false,
      duration
    };
    this.onClick = this.onClick.bind(this);
    this.onClickOff = this.onClickOff.bind(this);
  }

  onClick() {
    this.setState({
      in: true,
    });
  }

  onClickOff() {
    this.setState({
      in: false,
    });
  }

  render() {
   return (
     <div>
       <button onClick={this.onClick}>clickOn</button>
       <button onClick={this.onClickOff}>clickOff</button>
       <Transition
        onEntering={() => { console.log('on entering')}}
        onEntered={() => { console.log('on entered')}}
       in={this.state.in}
       timeout={this.state.duration}>
       {(state) => (
         <div style={{
           background: 'blue',
             ...defaultStyle,
             ...transitionStyles[state]
         }}>
         <div>
         <h2>This is Bar</h2>
         </div>
         </div>
       )}
       </Transition>
     </div>
   );
  }
}

ReactDOM.render(
  <Foo/>, document.getElementById('app')
);

Richardinho avatar Feb 01 '18 13:02 Richardinho

That's why I'm not using CSSTransition :)

Transition is enough, it works fine, what the problem?

loginov-rocks avatar Jul 18 '18 14:07 loginov-rocks

You said there was a problem:

Same problem, using v2.4.0

I was just trying to understand what it is.

silvenon avatar Jul 18 '18 15:07 silvenon

Any news about the delay on animations? I'm using a <CSSTransition> inside another one and I would that the second one starts with a delay.

@silvenon temporary can you make an example with your solution:

You can use setTimeout to delay whatever is setting the in prop to true.

Thanks

timhecker avatar Aug 23 '18 10:08 timhecker

I haven't tested this, but here's a (possibly naive) example:

import React from 'react'
import { CSSTransition } from 'react-transition-group'

const DELAY = 1000
const DURATION = 500

class MyComponent extends React.Component {
  state = {
    inProp: false,
  }
  
  timerId = null

  render() {
    const { inProp } = this.state;
    return (
      <div>
        <CSSTransition
          in={inProp}
          timeout={DURATION}
          classNames="fade"
        >
          {/* ... */}
        </CSSTransition>
        <button
          type="button"
          onClick={() => {
            this.timerId = setTimeout(() => {
              this.setState({
                inProp: true,
              })
            }, DELAY)
          }}
        >

        </button>
      </div>
    )
  }
}

Make sure to stop the timer with clearTimeout(this.timerId) when necessary, depending on your use case.

silvenon avatar Aug 23 '18 11:08 silvenon

Any changes? 2.4.0 still have timeout before starting anim(as @1oginov said).

Mati365 avatar Oct 29 '18 12:10 Mati365

This issue talks about two opposite things, to remove the delay and to add it. I provided the solutions to both, so please share some code and I'll help you get rid of the initial delay using CSSTransition.

silvenon avatar Oct 29 '18 15:10 silvenon

Any updates on this thread? I need children TransitionGroup to first exit and then enter, not wanting them to happen simultaneously. I can set delay in CSSTransition manually but a) it's ugly b) it will introduce a delay if appear is set. So is there a better solution? Or should I open an new issue?

std4453 avatar Nov 20 '18 02:11 std4453

The example in this comment solved it for me.

rppld avatar Nov 20 '18 15:11 rppld

@std4453 so you're trying to add a delay? Perhaps best to open a new issue with a demo and an detailed description of what you're trying to achieve.

silvenon avatar Nov 20 '18 21:11 silvenon

To those still having this issue: I was having the same issue and this is how I fixed it.

The documentation at: https://reactcommunity.org/react-transition-group/transition suggests that you should put your starting css styles in the "entering" state and your target css styles in the "entered" state. This is wrong, doing it this way causes a delay and heres why. Suppose we have the following setup:

defaultState: opacity: 0; transition: opacity 500ms; enteringState: opacity: 0; enteredState: opacity 1; timeout = 500

When this animation is played, the first 500 milliseconds "enteringState" will be applied. Note that there is no difference between the entering state and the default, thus nothing happens and this is seen as the "delay". After 500ms, the "enteredState" is applied and you will then see an animation because the "transition" css property was set to 500ms.

The reason why setting timeout=0 solved the problem for a lot of people could have been because with timeout set to 0, the "enteredState" gets applied right away and the CSS transition happens. This is wrong as the CSS animation and the Transition group timeout aren't lining up.

Solution:

The setup above should have been:

defaultState: opacity: 0; transition: opacity 500ms; enteringState: opacity: 1; <-- this is the only thing that changed. enteredState: opacity 1; timeout = 500

Now when "enteringState" is applied, the CSS transition will begin to happen right away and it will lineup with the Transition timeout. As a note, your "enteringState" & "enteredState" (and your "exitingState" & "exitedState") should be the same.

talham7391 avatar Apr 13 '19 21:04 talham7391

@talham7391 thanks for pointing this out, I wasn't aware of this problem in the docs, now this has been fixed. ✅

silvenon avatar Apr 14 '19 20:04 silvenon

@talham7391 entering state does not trigger the transition for me. The workaround I'm using right now is to set duration prop to { enter: 0, exit: duration }

jwm0 avatar Jul 29 '19 11:07 jwm0

@jwm0 if you pass 0 to enter value it is hightly possible that enter phrase will be not animated. I have tried that and sometimes component had appeared without any animation - try to set 60ms instead of 0. Browser engine will be able to set transitions correctly (without batching etc).

Mati365 avatar Jul 29 '19 12:07 Mati365

@Mati365 it feels hacky but I'll look into it - let me know if you remember any particular scenarios where it would not animate. Also, can you confirm that the solution @talham7391 provided also doesn't seem to be working for you?

jwm0 avatar Jul 29 '19 13:07 jwm0

This is how I fixed this, use transition-delay property in your enter-active and exit-active, that is not all you have to do, however.

The prop timeout, is the total duration of the animation, delay included, so if you're going to add the css transition property's duration, make sure the sum of the delay and the duration of the transition is equal to the timeout prop, for example:

.${classNames}-enter {
      opacity: 0;
      transform: scale(0.95);
    }
    .${classNames}-enter-active {
      opacity: 1;
      transform: scale(1);
      transition: opacity ${duration}ms, transform ${duration}ms;
      transition-delay: ${delay}ms;
    }

Where timeout would be equal to the sum of duration and delay. In my component, it looks like this:

  const delay = animationTimeout * 0.33 * animationMultiplier * animationDelayMultiplier;
  const duration = animationTimeout * 0.66 * animationMultiplier;

  ...

  return (
      <CSSTransition
        in={in}
        timeout={duration + delay}
        classNames={classNames}
        onEnter={onEnter}
        onExited={onExited}
        unmountOnExit={unmountOnExit}
      >
        ...

And here's an example of how it looks in production: https://i.gyazo.com/23172bc8d4a81ce03389e4c7da7dd7ee.mp4

rmolinamir avatar Sep 11 '19 02:09 rmolinamir

I had an issue getting the defaultState to render with @talham7391 solution, but agree that it looks correct.

With @jwm0 proposed solution of setting timeout={{ enter: 0, exit: duration }} I ran into the issue where sometimes the enter phase wasn't animated.

To get both working I created an interpretation layer between the Transition and children. Seemed to fix both issues while staying true to the model @talham7391 proposed.

const entering = 'entering';
const entered = 'entered';
const exiting = 'exiting';
const exited = 'exited';

const machine = {
  initial: 'default',
  states: {
    default: { entering },
    entering: { entered },
    entered: { exiting },
    exiting: { exited },
    exited: {},
  },
};

const reducer = (state, action) => machine.states[state]?.[action] || state;

// Used as an interpretation layer between Transition
// and children being called with state. Allows for first
// render of default styles while keeping timeout in sync
// with state.
export function Interpreter({ state, children }) {
  const [scheduledState, dispatch] = useReducer(
    reducer,
    state === entered ? state : machine.initial
  );
  const [nextRender, setNextRender] = useState(state);

  // Ensures we get a paint with every current state
  // we are on before we interpret an update.
  useEffect(() => {
    const id = requestAnimationFrame(() => setNextRender(state));
    return () => cancelAnimationFrame(id);
  }, [state]);

  // Use our state machine implementation to deterministically order state
  // transitions. Ensures following order & at least one render on each state:
  // default -> entering -> entered -> exiting -> exited
  useEffect(() => {
    dispatch(nextRender);
  }, [nextRender]);

  // We want to opt out of our expected behavior immediately if there's a premature
  // enter or exit scenario.
  //
  // It's important that these state changes are reflected on exactly this render,
  // as opposed to in the state machine, to prevent content flash where two children
  // of a transition group can both be in an `enter` or `exit` state in the same paint
  // when only one is entering and the other is exiting.
  const isPrematureExit =
    [entering, entered].includes(scheduledState) && state === 'exiting';
  const isPrematureEntrance =
    [exiting].includes(scheduledState) && [entering, entered].includes(state);
  const shouldUseBaseState = isPrematureEntrance || isPrematureExit;
  return children(shouldUseBaseState ? state : scheduledState);
}

export function ScheduledTransition({ children, ...props }) {
  return (
    <Transition {...props}>
      {(state) => (
        <Interpreter state={state}>
          {(scheduledState) => children(scheduledState)}
        </Interpreter>
      )}
    </Transition>
  );
}

Allowed me to use ScheduledTransition as a drop in replacement for Transition while solving all the problems discussed in this thread:

const duration = 300;

const transitionStyles = {
  entering: 'transform: none;',
  entered:  'transform: none;',
  exiting:  'transform: translateX(100%);',
  exited:  'transform: translateX(100%);',
};

const Controller = styled.div`
  // Default styles now applied on first render
  transform: translateX(-100%);
  transition: transform ${duration}ms ease-out;
  
  // Transition Styles apply in sequential renders
  ${({ state }) => transitionStyles[state]}
`;

const Fade = ({ in: inProp }) => (
  <ScheduledTransition in={inProp} timeout={duration} mountOnEnter unmountOnExit>
    {state => (
      <Controller state={state}>
        I'm a translate Transition!
      </Controller>
    )}
  </ScheduledTransition>
);

Please let me know if I'm misusing the package at all and there's no need for this middle layer. However, thought i'd mention here in case someone is running into the same issue because it seemed to fix it for me and provide reliable behavior

maxyinger avatar Feb 01 '21 17:02 maxyinger