4

I change the component that is rendered through a time interval.

I would like to be able to add an animation every time that change happens. What is the best way to go about it?

constructor (props) {
    super(props)
    this.state = { currentComponent: 1,
    numberOfComponents: 2}
}

componentWillMount() {
    setInterval(() => {
       if(this.state.currentComponent === 2) {
           this.setState({currentComponent: 1})
       } else {
           this.setState({currentComponent: this.state.currentComponent + 1})
       }
    }, 5000)
}

render(){

    let currentComponent = null;

    if(this.state.currentComponent === 1) {
        currentComponent = <ComponentOne/>;

    } else {
        currentComponent = <ComponentTwo/>;
    }

    return(
        currentComponent
    )
}

EDIT:

Also when trying to use 'react-addons-css-transition-group' I get the following error:

enter image description here

criver.to
  • 520
  • 2
  • 9
  • 18
  • The easiest in my opinion is using CSS3 transitions. You give your elements a class based on your state, which changes your element's styling. You can transition this styling using the CSS3 transitions (or CSS3 animations). – stinodes Jan 04 '17 at 23:07

1 Answers1

1

You can do with ReactCSSTransitionGroup like provided in this section

Your css:

.example-enter {
  opacity: 0.01;
}

.example-enter.example-enter-active {
  opacity: 1;
  transition: opacity 500ms ease-in;
}

.example-leave {
  opacity: 1;
}

.example-leave.example-leave-active {
  opacity: 0.01;
  transition: opacity 300ms ease-in;
}

Will look like this:

import ReactCSSTransitionGroup from 'react-addons-css-transition-group';



class MyComponent extends Component {
  constructor (props) {
    super(props)
    this.state = { currentComponent: 1,
    numberOfComponents: 2}
  }

  componentWillMount() {
    setInterval(() => {
       if(this.state.currentComponent === 2) {
           this.setState({currentComponent: 1})
       } else {
           this.setState({currentComponent: this.state.currentComponent + 1})
       }
    }, 5000)
  }

  render(){

    let currentComponent = null;

    if(this.state.currentComponent === 1) {
        currentComponent = <ComponentOne/>;

    } else {
        currentComponent = <ComponentTwo/>;
    }

    return(
        <ReactCSSTransitionGroup
          transitionName="example"
           transitionEnterTimeout={500}
          transitionLeaveTimeout={300}>
          {currentComponent}
        </ReactCSSTransitionGroup>

    )
  }
}
Lucas Katayama
  • 4,445
  • 27
  • 34