Menu

React Controlled Components: Forms & User Input Guide

Forms and User Input

Controlled Components

What is a Controlled Component?

In plain HTML, an input holds its own value in the DOM. In React, you usually store that value in state and tell the input to display it. An input whose value comes from React state is a controlled component.

Why is it Used?

Once the value lives in state, you get everything else for free: live validation, disabling the submit button until the form is valid, clearing the form after submission, and using the typed value elsewhere in the UI.

Syntax

jsx

const [value, setValue] = useState("");
<input value={value} onChange={e => setValue(e.target.value)} />

Two pieces make it controlled: value sets what is shown, and onChange updates the state.

Example

src/components/SearchBox.jsx

jsx

import { useState } from "react";
function SearchBox() {
const [query, setQuery] = useState("");
function handleChange(event) {
setQuery(event.target.value);
}
return (
<div>
<input
type="text"
value={query}
onChange={handleChange}
placeholder="Search courses"
/>
<p>Characters typed: {query.length}</p>
<button onClick={() => setQuery("")} disabled={query === ""}>
Clear
</button>
</div>
);
}
export default SearchBox;

How It Works

  • value={query} - the input always displays whatever is in state.
  • onChange fires on every keystroke and updates state, which re-renders the input with the new value.
  • disabled={query === ""} - the button is disabled while the box is empty, using the state value directly.

This loop — state renders the input, the input updates state is the core pattern for all React forms.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details