FadeIn and FadeOut effect using React JS

I have something like this:

var Hello = React.createClass({
    getInitialState: function(){
    return {
        opacity: 0
    }
  },

  handleClick: function(event){
    event.preventDefault();
    this.setState({opacity: 1});
  },

  render: function() {
    return <div>
        <div style={{opacity: this.state.opacity, transition: "opacity 1s"}}>Test</div>
      <a href="" onClick={this.handleClick}>Click</a>
    </div>;
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

Here jsfiddle

I want the div with the text test inside not to display when the page loads. Then, if I click on the link that the div shows. Here is what this example does.

But I want after the div appears after the click, in a few seconds it will disappear again. (I need to somehow set the opacity back to 0).

Any tips?

+4
source share
1 answer

You can add a FadeOut effect, passing the callback function to setState().

A simple solution would look like this:

handleClick: function(event){
    event.preventDefault();
    this.setState({opacity: 1}, () => setTimeout(() => this.setState({opacity:0}),4000)); 
},

jsfiddle

Will be better

handleClick: function(event){
    event.preventDefault();
    this.setState({opacity: 1}, () => {
        if(!this.timeout)
            clearTimeout(this.timeout);
        this.timeout = setTimeout(() => this.setState({opacity:0}),4000);
 });

jsfiddle

+5
source

Source: https://habr.com/ru/post/1650300/


All Articles