preventDefault() not preventing page refresh on form submit in React

I am currently building a form and somehow the page refreshes when the form is submitted, even though I call preventDefault() in onSubmit. Here is a minified version of my React form component:
import { FormEvent } from 'react';

function ContactForm() {
function sendEmail(event: FormEvent<HTMLFormElement>) {
event.preventDefault();

// send email logic
}

return (
<form
onSubmit={sendEmail}
>
<!-- input fields -->
<button
type="submit"
>
Submit
</button>
</form>
import { FormEvent } from 'react';

function ContactForm() {
function sendEmail(event: FormEvent<HTMLFormElement>) {
event.preventDefault();

// send email logic
}

return (
<form
onSubmit={sendEmail}
>
<!-- input fields -->
<button
type="submit"
>
Submit
</button>
</form>
Help is much appreciated! 🙂
4 Replies
vince
vince•2y ago
I've never used FormEvents but I know with regular html forms in React the way you're doing it should work. You have the sendEmail function on the form element, and you're calling e.preventDefault(). Problem might lie in FormEvent's functionality. I would look into that specifically and see if you can find anything about preventing default behavior
nickymicky
nickymicky•2y ago
try onSubmit={(e)=>sendEmail(e)}
LOKKEE
LOKKEEOP•2y ago
seems like this had actually something to do with the partial hydration of framework islands from Astro. Thank you for your help though! 😊
vince
vince•2y ago
Interesting! Glad you figured it out
Want results from more Discord servers?
Add your server