Kris Selbekk Kris Selbekk - 1 month ago 14x
React JSX Question

Fade out / in text when changing in React

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 className="half">
<button className="button" onClick={this.chooseRight}>{this.state.rightButton}</button>


I tried with
, 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.


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' : ''}`}>