Fade out / in text when changing in React

17,618

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.

Share:
17,618
Kris Selbekk
Author by

Kris Selbekk

Trying to make this place a bit more friendly. React, JavaScript, Java.

Updated on June 27, 2022

Comments

  • Kris Selbekk
    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
    Kris Selbekk about 8 years
    I 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
    ezakto about 8 years
    Did you add a delay in the CSS animation?
  • Kris Selbekk
    Kris Selbekk about 8 years
    nope didn't. Basically just tried what the React tutorial said, since they had a fade in example.
  • tomericco
    tomericco over 7 years
    Try this for fading out and then in: github.com/marnusw/react-css-transition-replace
  • Mo.
    Mo. almost 7 years
    Can we use React Lifecycle ?
  • uncleoptimus
    uncleoptimus over 6 years
    Yea 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 on componentDidUpdate to apply the fade-in then the effect would be nullified due to everything being executed too "quickly"