Fade out / in text when changing in React
Solution 1
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>
);
}
Solution 2
Use ReactCSSTransitionGroup, part of react's animation add-ons. It's designed for your exact use case.
Kris Selbekk
Trying to make this place a bit more friendly. React, JavaScript, Java.
Updated on June 27, 2022Comments
-
Kris Selbekk almost 2 years
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. -
Kris Selbekk about 8 yearsI tried the
ReactCSSTransitionGroup
, but then the old text sticks around while the new one is added. In other words - it didn't give me the effect I wanted. -
ezakto about 8 yearsDid you add a delay in the CSS animation?
-
Kris Selbekk about 8 yearsnope didn't. Basically just tried what the React tutorial said, since they had a fade in example.
-
tomericco over 7 yearsTry this for fading out and then in: github.com/marnusw/react-css-transition-replace
-
Mo. almost 7 yearsCan we use React Lifecycle ?
-
uncleoptimus over 6 yearsYea that would likely work as a "hook-in" point to run something along the lines of the above. E.g.
componentWillUpdate
apply fade-out with the timer to restore with fade-in. But I think if you relied oncomponentDidUpdate
to apply the fade-in then the effect would be nullified due to everything being executed too "quickly"