SmartCodingTips

πŸš€ Handling Form Submissions in React

Submitting a form in React is straightforward using the onSubmit event. Typically, we prevent the browser’s default behavior and use state to access form values.


πŸ“¨ Basic Example


function ContactForm() {
  const [email, setEmail] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevents page reload
    console.log("Form submitted:", email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email:
        <input 
          type="email" 
          value={email} 
          onChange={(e) => setEmail(e.target.value)} 
        />
      </label>
      <button type="submit">Send</button>
    </form>
  );
}

The handleSubmit function captures the form data without refreshing the page.

🧾 Submitting Multiple Fields


function SignupForm() {
  const [form, setForm] = React.useState({ username: "", password: "" });

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("User Data:", form);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        name="username" 
        value={form.username} 
        onChange={handleChange} 
        placeholder="Username" 
      />
      <input 
        name="password" 
        type="password" 
        value={form.password} 
        onChange={handleChange} 
        placeholder="Password" 
      />
      <button type="submit">Sign Up</button>
    </form>
  );
}

Using a single handleChange function makes it easier to manage multiple inputs.

πŸ’‘ Tips for Handling Submissions

  • Always use e.preventDefault() to stop default form behavior.
  • Perform validation before submission (client or server side).
  • Use state to access and manage form inputs.
  • Use loading indicators and error messages for better UX.