React Forms Objectives

Learning Goals

After completing this material, you will be able to:

Understanding Forms in React

Forms are essential for collecting user input in a React application. Unlike traditional HTML forms, React uses controlled components to manage form state.

Creating a Form Component

A simple form component in React looks like this:


function MyForm() {
  const [inputValue, setInputValue] = useState("");

  return (
    
setInputValue(e.target.value)} />
); }

Handling Multiple Inputs

Instead of writing separate handlers for each input, you can use a single event handler:


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

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

  return (
    
); }

Controlled Inputs

A controlled input is an input element whose value is controlled by React state.

Form Validation

You can implement validation inside the event handler:


function MyForm() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  const handleChange = (e) => {
    const value = e.target.value;
    setEmail(value);
    setError(value.includes("@") ? "" : "Invalid email format");
  };

  return (
    
{error &&

{error}

}
); }

Handling Form Submission

Use the onSubmit event to handle form submissions:


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

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Form submitted:", formData);
  };

  return (
    
setFormData({ ...formData, name: e.target.value })} /> setFormData({ ...formData, email: e.target.value })} />
); }

What You Have Learned

In this reading, you learned:

Further Exploration

To continue learning, visit:

Conclusion

Understanding forms in React is crucial for handling user input effectively. Controlled components ensure state synchronization, and event handlers allow for efficient input management.