Next

Forms Basics

  • This lesson introduces the basics of forms in React and explains how to handle user input and form submissions.

  • Topic Overview

    Forms are used to collect user input such as names, emails, passwords, etc.
    In React, forms are handled in a controlled and predictable way using state.

    Forms Basics

    A form is used to collect and submit user data.

    Common form examples:

    • Login form

    • Registration form

    • Contact form

    React handles forms differently from plain HTML.

    Form Elements in React

    React supports all standard HTML form elements.

    Common Form Elements:

    • <input>

    • <textarea>

    • <select>

    • <button>

    Example:

<form>
  <input type="text" />
  <button>Submit</button>
</form>
  • Controlled Components

    A controlled component is a form element whose value is controlled by React state.

    In simple words:
    React controls the input value.

    Example:

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

<input
  type="text"
  value={name}
  onChange={(e) => setName(e.target.value)}
/>
  • The input value always comes from state.

    Handling Input Changes

    React uses the onChange event to track user input.

    Example:

function handleChange(e) {
  setName(e.target.value);
}

<input type="text" onChange={handleChange} />
  • Each keystroke updates the state.
Next