onClick not working

So I have this “Get A Quote” button and whenever it’s clicked I’m setting a new state so the current quote and author in the html would change. Here’s some of my code regarding to how I’m changing the state:

state = {
        quote: 'No matter what you’re going through, 
there’s a light at the end of the tunnel..',
        author: 'Demi Lovato'

My this.setState code:

      quote: QUOTES[randomIndex].paragraph,
      author: QUOTES[randomIndex].author

The problem is it’s doing the opposite :frowning:

Yes, I declared my own array of quotes, it might be a dumb mistake or something I overlooked but please help me find it! Thanks!

Here’s the link to my codepen:
Random Quote Machine

1 Like

I see two issues.

Firstly, your click doesn’t fire anything because you haven’t applied it to anything that has an onClick event, I don’t think:

<a href="#" className="right"><i className="fa-solid fa-shuffle" onClick={this.handleChange}></i> Get a quote</a>

You can confirm that but putting a log statement in your handler function. That should be a first step in debugging - make sure it is running.

So, if I replace that with something that can fire that, I get to the next issue…


const randomIndex = Math.floor(Math.random() * QUOTES.length)

That is at a root level. It is run once and stores a number in that variable. The right side of that equation doesn’t get rerun every time that variable is accessed. That value will never change. You need to put that somewhere where it will get reevaluated every time you need a new quote.

When I fix those two things, I get a button that will give me a new quote on each press.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.