0
0
Reactframework~5 mins

Controlled components in React

Choose your learning style9 modes available
Introduction

Controlled components let you keep form data inside React state. This helps you manage and use the data easily.

When you want to update the UI based on user input immediately.
When you need to validate or format input as the user types.
When you want to enable or disable buttons based on form data.
When you want to submit form data from React state.
When you want to reset or clear form fields programmatically.
Syntax
React
function MyComponent() {
  const [value, setValue] = React.useState('');

  function handleChange(event) {
    setValue(event.target.value);
  }

  return (
    <input type="text" value={value} onChange={handleChange} />
  );
}

The value attribute sets the input's current value from React state.

The onChange event updates the state when the user types.

Examples
Simple controlled input with inline event handler.
React
const [name, setName] = React.useState('');

<input value={name} onChange={e => setName(e.target.value)} />
Controlled checkbox input using checked attribute.
React
const [checked, setChecked] = React.useState(false);

<input type="checkbox" checked={checked} onChange={e => setChecked(e.target.checked)} />
Controlled textarea element with state.
React
const [text, setText] = React.useState('Hello');

<textarea value={text} onChange={e => setText(e.target.value)} />
Sample Program

This component shows a text input controlled by React state. As you type, the text below updates instantly.

React
import React from 'react';

export default function ControlledInput() {
  const [inputValue, setInputValue] = React.useState('');

  function handleChange(event) {
    setInputValue(event.target.value);
  }

  return (
    <div>
      <label htmlFor="nameInput">Name: </label>
      <input
        id="nameInput"
        type="text"
        value={inputValue}
        onChange={handleChange}
        aria-label="Name input"
      />
      <p>You typed: {inputValue}</p>
    </div>
  );
}
OutputSuccess
Important Notes

Always set the value or checked attribute to keep input controlled.

Without onChange, the input will be read-only.

Use aria-label or label for accessibility.

Summary

Controlled components keep form data in React state.

Use value and onChange to sync input and state.

This helps with validation, formatting, and dynamic UI updates.