Hello, I have difficulties understanding why my onClick isn’t working.
So, I have a class component that renders a Button component with an onClick event listener attached to it, that should fetch a quote from a quote api and log it in the console, however this doesn’t happen. When I click the button, nothing happens.
In the Button component there is a <div> with a <button> inside. When I replace the Button component with an html <button> tag it works fine, but I want to use the component.
Any ideas?
My code:
import React from 'react'
import Button from './Button'
import Quote from './Quote'
class App extends React.Component {
state = { quote: 'i did it' }
getNewQuote = () => {
fetch("https://type.fit/api/quotes")
.then(function (response) {
return response.json();
})
.then(function (data) {
let randomNum = Math.floor(Math.random() * 1150);
console.log(data[randomNum]);
});
};
render(){
return (<div>
<Quote quote={this.state.quote}/>
<Button onClick={this.getNewQuote} text="New Quote"/>
</div>)
}
}
Browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0
I’ve edited your post. If you want inline HTML elements in your text, you need to surround them with single backticks, or the app will try to interpret them, like:
In the Button component there is a `<div>` with a `<button>` inside.
Just to be clear, onClick on the Button component is a prop and onClick on the button JSX element is the event. As said, you have to call the handler on the button JSX element.
That is also why, at least with components that look or act like elements, it can be a good idea not to name the props after events. Just to avoid any confusion. Although it isn’t that uncommon to do so.
Thank you very much.
I somehow got confused and forgot that that way I pass a prop to a component.
I will listen to your advice and try to separate them with different names and pay more attention.