Hello everyone, I already built a random quote machine in jquery but now I am trying it in React.
const quoteArray = ['quote1', 'quote2', 'quote3']
class Display extends React.Component {
constructor(props){
super(props);
this.state = {
DisplayedQuote: 'yeet'
}
};
getRandomQuote() {
const diffQuotes = quoteArray.filter(state => state !== this.state.DisplayedQuote);
const randomQuote = Math.floor(Math.random() * diffQuotes.length);
return diffQuotes[randomQuote];
}
render() {
return (
<React.Fragment>
<h1> {this.state.DisplayedQuote} </h1>
<button onClick={this.getRandomQuote()}> Change </button>
</React.Fragment>
Where is the error(s) in my code? I am trying to get a new quote from the QuoteArray and have it displayed in DisplayedQuote.
I am quite new to react, so sorry if I am making simple mistakes.
Full code in case needed:
snigo
November 23, 2019, 8:55am
2
Getting a new random quote is not enough here, as you need to trigger re-render and in React you would do this by setState(newstate)
1 Like
So where should I put the setState exactly?
In the onclick statement?
snigo
November 23, 2019, 9:14am
4
Inside your getRandomQuote()
- when you get it you need to update state
I haven’t found exactly where to put it yet, but I am making your answer as the solution just in case I forget.
Thanks for your help!
snigo
November 23, 2019, 9:27am
6
Try to put it instead of return
Sorry to bother you again, after getting lunch and coffee but I am still getting nothing.
this.setState.DisplayedQuote[randomQuote];
Is this how setState would be used in place of a return?
snigo
November 23, 2019, 10:55am
8
No, setState
is a function. So:
this.setState({ DisplayedQuote: diffQuotes[randomQuote] } );
1 Like
Thank you. Sorry for the excessive hand-holding I require. I am very bad with React.
<React.Fragment>
<h1> {this.state.DisplayedQuote} </h1>
<button onClick={this.getRandomQuote}> Change </button>
</React.Fragment>
So what is wrong with my onClick statement? It is working on the previous project I did.