reactjsreactcsstransitiongroup

How to fade text in, then out


I'm trying to make a notification next appear to a text input to inform the users their text was saved, and then fade that notification text out.

Basically I'm trying to replicate this action, when a corresponding text input is submitted.

$(this).fadeOut().next().fadeIn();

I can't think of any way to fade it in, then out, that isn't absurdly roundabout.

I'm using Redux as well, and would like to use that, but it's not a requirement. Any advice would be appreciated.


Solution

  • You can use CSS to take care of that. Here's a very simple example (not using redux). Use JS to trigger, CSS to style.

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          show: false
        };
        this.showNotification = this.showNotification.bind(this);
      }
      showNotification() {
        // You can use redux for this.
        this.setState({
          show: true,
        });
        setTimeout(() => {
          this.setState({
            show: false,
          });
        }, 1000);
      }
      render() {
        return (
          <div>
            <button onClick={this.showNotification}>Save</button>
            <Notification show={this.state.show} />
          </div>
        );
      }
    
    }
    
    class Notification extends React.Component {
      render() {
        return <span className={this.props.show ? 'show' : ''}>Saved!</span>
      }
    }
    
    ReactDOM.render(<App/>, document.getElementById('View'));
    span {
      transition: 300ms all ease;
      opacity: 0;
      will-change: opacity;
    }
    
    .show {
      opacity: 1;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="View"></div>