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!

1
  • Can you show the code of the submit button, because preventDefault() works for anchor tags with href and type='submit' buttons. Commented Apr 4, 2021 at 9:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.