π€ Form Submission in React
Submitting a form in React involves handling the submit event, collecting form values, and processing or sending them to a server. React's controlled components make this easy and flexible.
π 1. Handle Form Submission
Use the onSubmit
event handler on the <form>
tag:
import { useState } from 'react';
function ContactForm() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault(); // prevent page reload
alert(`Form submitted: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your Name"
/>
<button type="submit">Send</button>
</form>
);
}
π 2. Prevent Default Behavior
By default, form submission reloads the page. Use e.preventDefault()
to stop this and handle it manually in React.
π¦ 3. Send Data to a Server
You can send form data to an API using fetch()
or axios
inside the handleSubmit()
:
fetch('/api/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
})
.then(res => res.json())
.then(data => console.log(data));
β 4. Clear Form After Submit
Reset the state after a successful submission:
setName('');
With React, you have full control over what happens on form submission β whether itβs validation, API calls, or UI updates.