score:10

Accepted answer

React Native

To begin an animation on a change of props you can simply start your animation in componentDidUpdate. Here's an example:

componentDidUpdate(prevProps) {
    if (this.props.isOpen !== prevProps.isOpen) {
        this.state.animation.start();
    }
}

Assuming your animation is defined in the component's state.

React (Browser):

[Not relevant to this question but potentially useful.]

A simple way to do this is using CSS transitions. What you can do is give the panel component a CSS class for closed (or open but I find using the closed/collapsed as a style easier because then the default is open).

Then in your panel's render:

render() {
    const { isOpen } = this.props;

    return <div className={ 'panel' + (isOpen ? '' : ' closed') }></div>
}

And in your CSS:

.panel {
    /* some other styles */
    transition: .5s ease-in;
}

.closed {
    height: 0;
}

This way CSS can handle the animation logic and your concern of clicking the open/close button before the current animation has finished is addressed.

Here are the CSS transition docs: https://developer.mozilla.org/en-US/docs/Web/CSS/transition

Edit: A disadvantage of this method is that height must be explicitly set when the panel is open.

Here's a little example snippet:

function togglePanel() {
  const panel = document.querySelector('div.panel');
  if (panel.classList.contains('closed')) {
    panel.classList.remove('closed');
  } else {
    panel.classList.add('closed');
  }
}
.panel {
  background-color: #00c0de;
  height: 4rem;
  overflow: hidden;
  transition: .5s ease-in;
}

.closed {
  height: 0;
}
<button onclick='togglePanel()'>Toggle Panel</button>

<div class='panel closed'>
  <span>Hello, I'm the panel</span>
</div>


Related Query

More Query from same tag