1

I am new to React/Next development. I have the code below:

import React from "react";

const Car = () => {
  var carCounter = 0;

  function addCar(event) {
    event.preventDefault();
    carCounter++;
    console.log(carCounter);
  }

  return (
    <form>
      <span className="car">
        <button class="big-button" onClick={addCar()}>
          Add Car
        </button>
      </span>
    </form>
  );
};

export default Car;

Obviously, this code is simplified. The root of my error was that the form was submitting when I pressed the button. However, the purpose of the button was to not "submit" the form. Rather, it was to increment a counter.

This is the error that was thrown above:

TypeError: Cannot read property 'preventDefault' of undefined

I went based of this thread:

https://stackoverflow.com/questions/39809943/react-preventing-form-submission#:~:text=Simply%20add%20onSubmit%3D%7BhandleSubmit,stop%20the%20default%20submission%20behavior.

Let me know what I can do!

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
Juliette
  • 4,309
  • 2
  • 14
  • 31
  • Can you show the code of the submit button, because `preventDefault()` works for anchor tags with `href` and `type='submit'` buttons. – Marios Nikolaou Apr 04 '21 at 09:28

1 Answers1

1

When providing onClick handler to the button, you need to write:

<button class="big-button" onClick={addCar}>Add Car</button> 
//         removed the () in addCar      ^

Then, it will pass the event to the addCar method.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87