Vicens Fayos
Vicens Fayos

Reputation: 760

Animation CSSTransition React

Using CSSTransition component and React I want to apply a Fade In animation

here you can find a small example what I want to achieve: https://codesandbox.io/s/j75712qjvy

On first load time text is faded in but never again when some of the buttons below are clicked.

Each time I click in one button, state is updated and component re-rendered. So my expectation is the fadeIn animation should restart.

What I overlook?

Upvotes: 2

Views: 631

Answers (1)

Ted
Ted

Reputation: 14937

You don't need the CssTransition to achieve this effect. It can be done with just CSS and the use of the key property on the element.

See this working demo

The key pieces of code are your element:

<h2 className="fadeIn" key={this.state.value}>
  {this.state.value}
</h2>

which I added the key and className props to. This tells react to replace it when the key changes.

Next is the associated CSS:

.fadeIn {
  animation: 1s fadeIn;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

This applies a fading in animation every time the element is re-rendered.

Note: The react-transition-group is only needed to achieve an exit transition effect. Entry transition effects can easily be handled without it.

Upvotes: 6

Related Questions