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: