React.js -- How to add an animation when unmounting a component and mounting another?

6k views Asked by At

I have this code for unmounting and remounting elements:

import React, { Component } from 'react';
import './App.css';
import Header from './Header';
import Bottom1 from './Bottom1';
import Bottom2 from './Bottom2';
class App extends Component {
  constructor(){
    super();
    this.state={
      playWindow: true
     }
     this.update = this.update.bind(this);
  }

  update(){
    const newState = this.state.playWindow? false : true;
    this.setState({playWindow: newState});
  }

  render() {
    return (
      <div className="App">
        <Header update={this.update}/>
        {this.state.playWindow?  <Bottom1/>  : <Bottom2/> }
      </div>
    );
  }
}

export default App;

When I do the action, the components are exchanged. The problem is that there is no transition, the toggle fells rough. How do I add an animation, like one fading out, and then the other fading in?

1

There are 1 answers

0
bennygenel On

You can animate components with react-transition-group. Check the docs here.

Example from the official docs:

class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {items: ['hello', 'world', 'click', 'me']};
    this.handleAdd = this.handleAdd.bind(this);
  }

  handleAdd() {
    const newItems = this.state.items.concat([
      prompt('Enter some text')
    ]);
    this.setState({items: newItems});
  }

  handleRemove(i) {
    let newItems = this.state.items.slice();
    newItems.splice(i, 1);
    this.setState({items: newItems});
  }

  render() {
    const items = this.state.items.map((item, i) => (
      <div key={item} onClick={() => this.handleRemove(i)}>
        {item}
      </div>
    ));

    return (
      <div>
        <button onClick={this.handleAdd}>Add Item</button>
        <ReactCSSTransitionGroup
          transitionName="example"
          transitionEnterTimeout={500}
          transitionLeaveTimeout={300}>
          {items}
        </ReactCSSTransitionGroup>
      </div>
    );
  }
}