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) => { e.preventDefault(); const newFact = {Email, Fact, Source}; console.log(newFact); } 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> <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(e.target.value)} required></input> </div> <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(e.target.value)} required></input> </div> <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(e.target.value)} required></input> </div> <div class="modal-footer"> <button class="btn btn-outline-dark">Submit</button> </div> </form> </div> </div> </div> </div> ) } 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: https://www.youtube.com/watch?v=pJiRj02PkJQ And heres a link to the source code of that tutorial: https://github.com/iamshaunjp/Complete-React-Tutorial/blob/lesson-28/dojo-blog/src/Create.js
Advertisement
Answer
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.