2
//sample piece of codes

constructor() {
    super()
  this.state.opacity= '0'
  this.state.mover = 'translateY(-40%)'
 }


this.setState({opacity:'1'})
this.setState({mover: 'translateY(-900%)'}, () => {this.setState({opacity:'0'})})

when I click on a button, I want a div to appear (using opacity 1) and transition to top and fade out after reaching the top(using opacity 0).

But it didn't work the way I expected. Currently, it fades out instantly. It doesn't wait for the transition to end. I want it to fade out after the transition ends.

Is there a way in React to fix it ? I am very new in react. Help is much appreciated. Thanks.

Ahmad
  • 816
  • 2
  • 9
  • 15
Edwin Varghese
  • 473
  • 1
  • 5
  • 15
  • I think the only way to solve this issue is using 'react-transition-group'. I have to do a POC to confirm though. https://reactcommunity.org/react-transition-group/ – Edwin Varghese Aug 13 '21 at 12:39

2 Answers2

2

Found an easy workaround for this. I am not sure if this is the right way, but it works.

constructor() {
super()
this.state.opacity= '0'
this.state.mover = 'translateY(-40%)'
}


this.setState({opacity:'1'})
this.setState({mover: 'translateY(-900%)'}, () => {
               setTimeout(() => { this.setState({ opacity: '0' })}, 1000);
               })

Inside the call back function, I setup a settimeout function. The event inside the settimeout function will be triggered after xxx milliseconds. So basically you will have to calculate the duration of your previous transition and set the time accordingly.

Edwin Varghese
  • 473
  • 1
  • 5
  • 15
  • 1
    This is definitely not the right way... in general you shouldn't be hard-coding setTimeouts like that. It's not really a big deal in this context, but I'd also consider using CSS animations. – AshotN Sep 08 '21 at 05:06
0

How about using transitionend event listener?

yourDivElement.addEventListener('transitionEnd', (event) => { 
   this.setState({ yourProp: "your-new-value" })
}, false );

Annoyingly enough, you may need to add different event names for cross browser compatibility:

["transitionend", "webkitTransitionEnd", "mozTransitionEnd"].forEach((eventName) => {
    yourDivElement.addEventListener(eventName, (event) => { 
       this.setState({ yourProp: "your-new-value" })
    }, false );
})

Make sure you refer to the DOM element using ref.

Browser compatibility Source

Norbert Biró
  • 636
  • 7
  • 16