Tell us what’s happening:
I’m trying to have the button change text whenever I click on it, but it’s not working, wondering where I went wrong. Trying to do it with React by the way.
To give more context, I want to move into the second return() when I click on the button the first time, and have the original text appear only at first load of the page. Whenever you click on it, the text in the button should change to “give me another one”. Once that works, I can start working on including the quote/author into the code, since if it’s not working the way I intended, then I’d rather go about another way rather than getting booged down in a way that doesn’t work.
Your code so far
Here’s my codepen:
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36
Your click handler is never fired because you misspelled the method name here:
onClick={this.handleclick}
And a little advice…
First of all, your constant quotes can be moved to the top or bottom of the pen, out of the way.
Secondly, rather than have separate returns for the Quotes component, you could just conditionally render things. I would also say that if you are going to keep a count, then I don’t think that you need to keep btnQuote in state. What if you button was something like:
<button
class="btn btn-primary"
id="new-quote"
onClick={this.handleClick}
>
{this.state.counter === 0 ? 'Yes, give me a random quote!' : 'Give me another one!'}</button>
That logic could be shortened to:
{this.state.counter ? 'Give me another one!' : 'Yes, give me a random quote!'}
You might even do that logic in the render method and store the string in a variable, to make things cleaner.
Similarly, the “Tell me why” thing could be rendered conditionally:
{ !!this.state.count && <p>Tell me why</p> }
These are very common patterns in React. They are easy shortcuts. It’s important to not get too carried away and end up with difficult to read code, but used wisely, they will make your code easier to read.
Thanks for the help! It’s pretty helpful getting things shown from a different perspective and I appreciate it. As for the “Tell me why”, it was just a placeholder, I never planned to keep it there.