CONTROLLED COMPONENTS /// HANDLE SUBMIT /// PREVENT DEFAULT /// FORM VALIDATION /// USESTATE HOOKS /// REACT FORMS MASTERCLASS ///

React Forms

LEVEL: ADVANCED INTERMEDIATE // SOURCE: CODE SYLLABUS

ReactForms.js
1 / 5
πŸ“

TUTOR: In React, forms are 'Controlled Components'. This means the React state is the 'single source of truth' for the input values.

The "Controlled" Pattern

In a standard HTML form, the DOM itself handles the state of inputs. In React, we invert this control. By linking the value of an input to a React state, we ensure that React is the only source of truth.

Why Controlled?

  • Instant validation feedback.
  • Easy to disable/enable buttons based on state.
  • Perfect for multi-step forms.
  • Simplified data formatting on the fly.

Validation Snippet

if (email.length < 5) { setError("Email too short"); }

Preventing Default Behavior

Browsers naturally want to refresh the page when a form is submitted. In a Single Page Application (SPA), this is catastrophic. We intercept the event with e.preventDefault() to handle data via Fetch API or Axios without losing our app context.

React Forms Glossary

Controlled Component

An input whose value is controlled by React state.

Uncontrolled Component

Inputs that maintain their own internal state (using Refs).

onChange

Event handler that fires every time the input value changes.

onSubmit

Event handler triggered when the form is submitted.

e.preventDefault()

Method used to stop the browser's default reload on submit.

Formik / React Hook Form

Popular libraries to manage complex form states and validation.