beauchette
beauchette

Reputation: 1124

css transitions ignored because react rerenders

I'm trying to use css transitions, but as react re-renders a component, they are getting ignored. Let's imagine the use case, in which my render() function outputs something like this:

<ul>
  <li className={this.state.path==="/menu1/" ? "active" : "inactive"}>
    menu 1
  </li>
  <li className={this.state.path==="/menu2/" ? "active" : "inactive"}>
    menu 2
  </li>
  <li className={this.state.path==="/menu3/" ? "active" : "inactive"}>
    menu 3
  </li>
</ul>

Let's imagine that:

The app loads with /menu1 being active. Using react router I update the state and the component should update. When navigating to a new route (eg "/menu2/") everything works, but as a re-rendering occurs, my transition gets ignored.

The only solution I saw was to modify the DOM using componentDidUpdate, but I don't want react to manipulate the DOM directly, so my question is :

How can I animate elements properly using react together with css?

Upvotes: 2

Views: 2984

Answers (1)

paulmorar
paulmorar

Reputation: 353

The correct way would be to use css modifiers for applying different styles.

This means that your code should look something like this:

<ul>
  <li className={`nav-item ${this.state.path==="/menu1/" ? "nav-item--active" : ""}`}>
    menu 1
  </li>
  <li className={`nav-item ${this.state.path==="/menu2/" ? "nav-item--active" : ""}`}>
    menu 2
  </li>
  <li className={`nav-item ${this.state.path==="/menu3/" ? "nav-item--active" : ""}`}>
    menu 3
  </li>
</ul>

Let's say you want a background transition. You would apply the transition styles and the initial background colour to the .nav-item class. And after that you will add a rule for .nav-item--active that just changes the background colour. I think by doing this you will get the expected result.

Upvotes: 0

Related Questions