Nearby lessons

20 of 44

📝 ReactJS – Forms

📌 What are Forms in React?

Forms are an integral part of any modern web application. They allow users to interact with the application and gather information such as login details, search input, booking data, and more.

In React, forms are handled differently compared to plain HTML, as React provides a more controlled and state-driven approach.

📋 What are Forms?

A form can contain input fields like text boxes, checkboxes, radio buttons, and buttons. Traditionally, in plain HTML, submitting a form triggers the browser to load a new page.

While this works fine in static websites, in dynamic applications it becomes inefficient and harder to manage.

⚠️ Problems with Normal HTML Form (in React)

When we create a normal form in React without handling submission or input state, developers face several issues:

  • Page Reloads: Every submission refreshes the page, breaking the single-page app experience.
  • No State Management: Input values are not linked with React state, so we cannot reuse them later.
  • Difficult Validation: Validating user input in real-time becomes hard without event handling.
  • Data Loss: On reload, all entered data is lost.

Here’s an example of such a form inside React:

React Playground
import React, { createContext } from 'react';
import NormalForm from './NormalForm.jsx';
const App = () => {
  return (
    <div>
      <NormalForm/>
    </div>
  );
}

export default App;

✅ Why React Forms?

React solves these problems by introducing controlled components, where form inputs are linked with component state using the useState hook. This gives full control over form data, validation, and submission handling without page reloads.

React Playground
import React, { createContext } from 'react';
import ControlledForm from './ControlledForm.jsx';
const App = () => {
  return (
    <div>
      <ControlledForm/>
    </div>
  );
}

export default App;

🔀 Controlled vs Uncontrolled Forms

1. Controlled Components

A controlled component is a form element that is controlled by React state. The input value is always driven by the component’s state, and any change updates the state through onChange handlers.

  • React fully controls the input field.
  • Easy to validate, track, and manipulate input values.
  • Preferred in most modern React applications.

2. Uncontrolled Components

An uncontrolled component is a form element that maintains its own internal state. Instead of using React state, you rely on ref to access values when needed.

  • DOM itself controls the input field.
  • Less code, but harder to manage in large apps.
  • Used rarely, when you don’t need React-driven validation or state sync.
Keep Going!React - Controlled Components