React onClick listener doesn't work

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

Challenge: Build a Random Quote Machine

Link to the challenge:

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. 

… but I want to use the [Button] component.

From what library does this come?

It is a Component that I made.
Here is the code.

import React from "react";

class Button extends React.Component {
    
  render() {
    return (<div>
        <button className="btn new-quote">
          {this.props.text}
        </button>
        </div>
    );
  }
}

export default Button;

Your Button component…

You pass in an onClick but then you never use that in your Button component. You need to pass that to the button element.

When I do that, it works for me.

1 Like

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.

1 Like

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.

Thank you very much for your replay.
I got confused and forgot the difference between passing a prop to a component and adding a event listener.