SmartCodingTips

πŸ“€ 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.