Gazowski
Gazowski

Reputation: 66

Nothing append with onAnimationEnd on React

I have a problem using onAnimationEnd on React. i have an overlay div and i change its class in 4 steps (with setState) :

  1. initial step : overlay div class = displayNone
  2. step 2 : a button with onClick event display the overlay div with class = fade-in
  3. step 3 : a button in the overlay with onClick event change class to fade-out
  4. step 4 : an onAnimationEnd event on the overlay div should change class to displayNone

But step nothing happen on step 4, the class stay on fade-out What i'm doing wrong ?

Thank you

code is here:

class Buttons extends React.Component{
  constructor(props){
    super(props)
    this.buttons = ['Hello Overlay','Goodbye Overlay']
    this.state = {
      overlayClass : 'displayNone',
    }
  }
  
  render(){
    return(

     <div>
        <h1>Overlay fade-in fade-out</h1>
          <button type='button' 
            onClick={() => this.setState({ overlayClass : 'fade-in' })}>{this.buttons[0]}</button>
        <div className={`overlay ${this.state.overlayClass}`}
          onAnimationEnd={() => this.setState({ overlayClass : 'displayNone' })}>
          <button type='button' 
            onClick={() => this.setState({ overlayClass : 'fade-out' })}
             >{this.buttons[1]}</button>
        </div>
      </div>
  )}
  
}
ReactDOM.render(<Buttons />, document.body);

Upvotes: 0

Views: 1345

Answers (1)

Dima Mamchur
Dima Mamchur

Reputation: 1099

So first of all in the codepen you've provided you were using some ancient version of React and ReactDOM - for some reason it was not working correctly with onAnimationEnd event. With the latest version of React it's working properly.

Here's fixed codepen

Notice that in handleAnimationEnd method I'm checking for current overlayClass to be fade-out because onAnimationEnd fires each animation so when you're changing overlayClass from fade-in to displayNone you'll never see the 'Goodbye Overlay' button.

Upvotes: 2

Related Questions