I need help getting my new quote button to work!

Tell us what’s happening:
Hey guys, I think I’m getting close with this React Component for the Random Quote Machine project, only thing is that when I click the button it isn’t actually bringing up a new quote. I have a big array of objects called “quotes” in my code, with properties for text and author, and the onClick for the button is set to the randQuote function, which is supposed to randomly select an object from the quotes array and then set the state to match it’s properties. My theories are that either something is wrong with the way I’m generating a random number, so it’s giving me the same quote every time, or else there’s something more fundamental about React component lifecycle that I might be missing. Any help would be greatly appreciated! Thanks so much.

Your code so far

 class QuoteBox extends React.Component {
 constructor() {
 super(); 
this.state = {
  quote: '',
  author: ''
};
this.randQuote = this.randQuote.bind(this);  
}

randQuote() {
let randomNumber = Math.floor(Math.random() * quotes.length);
this.setState(state => ({
quote: quotes[randomNumber].text,
author: quotes[randomNumber].author
}))
}

render() {
return (
  <div>
   <h2 id='text'>{this.state.quote}</h2>
    <h3 id='author'>-{this.state.author}</h3>
   <button id="new-quote" onClick={this.randQuote()}>New Quote!</button>
  </div>
     );
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36.

Challenge: Build a Random Quote Machine

Link to the challenge:

Hello there,

The only thing I can see that would cause unexpected behaviour is:

onClick={this.randQuote()}

Remember, properties/attributes like onClick (onclick) take a function handle, not a function call.

To elaborate:

Currently the code is read as:

  • The value for onClick is equal to the result (what is returned) of calling the function randQuote. So, seeing as randQuote returns undefined, onClick=undefined.

This behaviour is often confusing, because the function does end up being called - when the button element is updated/mounted.

Hope this helps

1 Like

Thank you so much! Literally just needed to delete the parentheses :’) Really appreciate the help!