Skip to content

Reactjs prevent form submission not working

I’m following a tutorial and I’m trying to have a form that does not reload when submitted to do this I’m trying to use e.preventDefault(); however this is not working and the page is reloading on submission anyway

here is my code:

import React from 'react';
import { useState } from 'react';

function Modal() {

    const [Email, setEmail] = useState('');
    const [Fact, setFact] = useState('');
    const [Source, setSource] = useState('');

    const handelSubmit = (e) => {
        const newFact = {Email, Fact, Source};

  return (
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Add a Fact</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            <div class="modal-body">
                <form onsubmit={handelSubmit}>
                    <div class="mb-3">
                        <label for="InputEmail" class="form-label">Email address</label>
                        <input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="enter your email..." value={Email} onChange={(e) => setEmail(} required></input>
                    <div class="mb-3">
                        <label for="InputFact" class="form-label">Fact</label>
                        <input type="text" class="form-control" id="InputFact" aria-describedby="emailHelp" placeholder="enter your fact..." value={Fact} onChange={(e) => setFact(} required></input>
                    <div class="mb-3">
                        <label for="InputSource" class="form-label">Source</label>
                        <input type="url" class="form-control" id="InputSource" aria-describedby="emailHelp" placeholder="enter your source..." value={Source} onChange={(e) => setSource(} required></input>
                    <div class="modal-footer">
                        <button class="btn btn-outline-dark">Submit</button>

export default Modal

the only major thing different that I’m doing from the tutorial is using a bootstrap 5 modal, but I don’t think that this would cause the problem

I was following this tutorial: And heres a link to the source code of that tutorial:



You have a typo in onsbumit. Change it to onSubmit. Remember that React is using JSX, so even though the code looks like HTML, it is actually JavaScript.

User contributions licensed under: CC BY-SA
2 People found this is helpful