1

I'm noticing some strange behavior with forms in react. I'm using a button with a handleSubmit function for the onClick attribute, but it is not technically a submit button for the form. Nevertheless, parts of the handleSubmit function are not working even when they are exactly the same lines of code from other functions. I believe the form is submitting on click of the button, but I have not designated this button as a submit button for the form. It's just a button.

<button
    class="button is-dark"
    onClick={(e) => handleSubmit(e, listItem.album.albumid, document.getElementById('scoreNum'+ listItem.index).value, listItem.index)}
    disabled={setDisabledInputs()}
>
    Submit
</button>

This function works fine:

const onClear = (item) => {
    document.getElementById('scoreNum' + item).removeAttribute("value")
    document.getElementById('scoreRange' + item).value = document.getElementById('scoreRange' + item).defaultValue
}

When I use one of the same lines of code in the handleSubmit function, it doesn't work, and the page refreshes as if the form has been submitted unless I use event.preventDefault():

const handleSubmit = (event, albumid, rating, item) => {
    document.getElementById('scoreNum' + item).removeAttribute("value") //why doesn't this work
}

I would expect the handleSubmit function to just do the code I wrote and nothing else.

  • 1
    Any ` – Pointy Jan 29 '23 at 21:29
  • 1
    Every button in a form is a submit button. You have to specify `type="button"` to disable this behaviour – Konrad Jan 29 '23 at 21:29

1 Answers1

0

Yes, if you have one button in a form element, this automatically becomes the submit button, unless it is given a different type attribute.

Also, i wouldn't name the eventHandler on the button as onSubmit, as you don't submit the button, you submit the form. This may cause confusion as you are not handling a submit event, you are handling a click event.

What you should declare in the callback function is e.PreventDefault() calling the PreventDefault method stops the page from trying to complete the submit event and thus stops the page refreshing.

Venex
  • 101
  • 7