John Huang
John Huang

Reputation: 348

Adding animated effect of fading out with react after a click event to change background color

I am working on a simple project called random quote machine on freecodecamp and I have already finished most of it. However, I am wondering how to add the animated effect of fading out right after clicking on the button to change the background and font color(Actually this link shows the effect I want for my project). Here is the link to what I've written so far.

  var colorsForBackground = [
  '#16a085',
  '#27ae60',
  '#2c3e50',
  '#f39c12',
  '#e74c3c',
  '#9b59b6',
  '#FB6964',
  '#342224',
  '#472E32',
  '#BDBB99',
  '#77B1A9',
  '#73A857'
];
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      quote: "",
      author: "",
      color:'#16a085',
    };
    this.handleClick=this.handleClick.bind(this)
  }
  handleClick(){
    fetch('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json')
    .then(response=>response.json())
    .then(data=>{
          const randomIndex=Math.floor(Math.random()*data.quotes.length)
          const randomIndexForColor=Math.floor(Math.random()*colorsForBackground.length)
          this.setState({
         quote:data.quotes[randomIndex].quote,
         author:data.quotes[randomIndex].author,
         color:colorsForBackground[randomIndexForColor]
    })})
  }
  render() {
    const tweetHref=`https://twitter.com/intent/tweet?text=${this.state.quote}-${this.state.author}&hashtags=quotes`
    return (
      <div id="gird-container" style={{backgroundColor:this.state.color}}>
        <div id="quote-box" className="container">
          <div id="text">{this.state.quote}</div>
          <div id="author" style={{color:this.state.color}}>{this.state.author}</div>
          <div className="flexContainer">

            <a id="tweet-quote" href={tweetHref} target="blank_"><i id="tweetIcon" className="fab fa-twitter-square fa-3x"style={{color:this.state.color}}></i></a>                 
            <button id="new-quote" onClick={this.handleClick} style={{backgroundColor:this.state.color}}>New quote</button>
            
          </div>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

Upvotes: 0

Views: 363

Answers (1)

Priyank Kachhela
Priyank Kachhela

Reputation: 2635

You need to add transition property in your #gird-container. You can change transition-duration as per your need. For demo purpose, I had set it to 1 second.

transition: background-color 1s ease;

Working demo here: https://codepen.io/priyank_kachhela/pen/YzZVNwR

For more information on transition property you can follow this link

Upvotes: 1

Related Questions