I am trying to use ReactCSSTransitionGroup
to replace content by fading out some content, waiting for it to disappear completely, and then fading in new content.
I am using key
props which was the solution to this related question, so the content is being swapped out and animated. The problem, though, is that the new content is added to the DOM and takes up space in the flow from the start, rather that waiting until the old content has faded out. i.e., I can delay fading in with a transition delay, but the gap where the content will fade in is there from the start. Since CSS visibility:hidden
still adds space for the element in the flow using that with opacity
doesn't help either.
My question: Is there a way to achieve the desired outcome using only CSS? If not, I presume my component will have to detect the end of the fade-out transition and only then add the new element; what is the recommended React way for detecting and reacting to transitionend
events?
My code thus far:
// jsx
let key = this.state.adding ? 'addForm' : 'addPlaceholder';
<ReactCSSTransitionGroup transitionName="fade">
<div key={key}>
{this.state.adding ? this.renderForm() : this.renderPlaceholder()}
</div>
</ReactCSSTransitionGroup>
// css
.fade-enter {
overflow: hidden;
opacity: 0.01;
}
.fade-enter.fade-enter-active {
opacity: 1;
transition: opacity .3s ease-in .3s;
}
.fade-leave {
opacity: 1;
}
.fade-leave.fade-leave-active {
opacity: 0.01;
transition: opacity .3s ease-in;
}
Just use a conditional class and CSS. Have a state variable like visible . So depending upon the state. visible the input will have a class of either fadeIn or fadeOut .
In the CSS, use the @keyframes rule paired with fadeIn. At 0%, set the opacity to 0. At 100%, set the opacity to 1. This creates the fade-in effect.
I have published a component, fade-props
, which addresses this problem specifically.
Under "Rendering a Single Child", the react docs say "This approach wouldn't work when animating multiple children or replacing the single child with another child"; so what you are tyring to do would be tricky with the available API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With