How To Handle Forms In React? See Example

Forms in React are typically handled using controlled components, where form inputs are bound to state. This allows React to fully control form data.


Controlled Components Example

import React, { useState } from "react";

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Submitted Name: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Key Points About Forms

  • Bind input values to state
  • Use onChange to update state
  • Prevent default form submission with event.preventDefault()
  • Forms can have multiple fields using separate state variables or an object state

Handling Multiple Inputs

function MyForm() {
  const [formData, setFormData] = useState({ name: "", email: "" });

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

  return (
    <form>
      <input name="name" value={formData.name} onChange={handleChange} />
      <input name="email" value={formData.email} onChange={handleChange} />
    </form>
  );
}

Conclusion

Forms in React are powerful when managed with controlled components. They allow you to capture, validate, and handle data efficiently.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *