Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: handleClick is not defined - React

I'll go straight to the point. This is the component I have in a ReactJS application:

class BooksList extends Component {

  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);

  }

  handleClick() {
    e.preventDefault();
    console.log("The link was clicked");
  }

  render() {
    return (
      <div>
        <a className="btn btn-success" onClick={handleClick}>
            Add to cart
        </a>
      </div>
    );
  }
}

Why do I get the following error when the component is loaded?

Uncaught ReferenceError: handleClick is not defined

EDIT:

After you answers I changed my code to this:

  handleClick(e) {
    e.preventDefault();
    console.log("Item added to the cart");
  }


  renderBooks(){
      return this.props.myBooks.data.map(function(book){
          return (
                  <div className="row">
                    <table className="table-responsive">
                      <tbody>
                        <tr>
                          <td>
                            <p className="bookTitle">{book.title}</p>
                          </td>
                        </tr>
                        <tr>
                          <td>                                  
                             <button value={book._id} onClick={this.handleClick}>Add to cart</button>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
          );
      });
    }
  }

render() {
    return (
      <div>
        <div>
          <h3>Buy our books</h3>
              {this.renderBooks()}
        </div>
      </div>
    );
  }

As you can see I have .map which iterate through a list of books. For each of the books I have a button that, if clicked, will add the specific book to the user's cart.

If I follow @Tharaka Wijebandara answer I can make a button work outside .map but in this case I still get the error:

Uncaught (in promise) TypeError: Cannot read property 'handleClick' of undefined
    at http://localhost:8080/bundle.js:41331:89
    at Array.map (native)
like image 677
splunk Avatar asked Oct 23 '25 23:10

splunk


1 Answers

Use this.handleClick

<a className="btn btn-success" onClick={this.handleClick}>
  Add to cart
</a>

and you have forgot to add e as an argument in your handleClick method.

handleClick(e) {
  e.preventDefault();
  console.log("The link was clicked");
}
like image 79
Tharaka Wijebandara Avatar answered Oct 26 '25 12:10

Tharaka Wijebandara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!