Reputation: 7624
I want to create a button that changes its text based on the state of the application. I want the old text to fade out, and then the new text to fade in.
Here's a pen where I've implemented what I want in pure JS.
How would I achieve the same effect in React - or what would be the best approach?
For reference, here is my JSX:
<div className="buttons">
<div className="half">
<button className="button" onClick={this.chooseLeft}>{this.state.leftButton}</button>
</div>
<div className="half">
<button className="button" onClick={this.chooseRight}>{this.state.rightButton}</button>
</div>
</div>
Edit:
I tried with ReactCSSTransitionGroup
, but it didn't work quite as expected. It added the new text, then faded out the old one while fading in the new one.
Upvotes: 3
Views: 21126
Reputation: 380
Had a similar use case and ended up using a timer to update a couple state variables.
One state var to track the message text, another to track application of a fade
class in the components className
. The fade
class basically controls opacity of the text block.
For instance:
...
// in some handler code
this.setState({fading: true}); // fade out
this.timer = setTimeout(_ => {
this.setState({msg: 'Some new text'}); // swap the text
this.setState({fading: false}); // fade back in
}, 500); // animation timing offset
// in render
render() {
const {msg, fading} = this.state;
return (
<h1 className={`${fading ? 'faded' : ''}`}>
{msg}
</h1>
);
}
Upvotes: 2
Reputation: 3194
Use ReactCSSTransitionGroup, part of react's animation add-ons. It's designed for your exact use case.
Upvotes: 4