CodeBlanks Logo Icon CodeBlanks

Controlled form

Learn the controlled form component.

What is a controlled form?

A controlled component is an input whose value is managed by React state. In React Native a controlled TextInput gets its value prop from state and updates state on every keystroke via onChangeText.

Example: you open state with const [name, setName] = useState("");; then you write <TextInput value={name} onChangeText={setName} />. The input now always holds the value React knows; to read it you just look at name. This pattern keeps form data in a single source of truth; it makes validation and submission easier. Uncontrolled inputs carry their own internal state and are hard to keep in sync with React.

value and onChangeText

A controlled TextInput takes two props. The value prop is the text the input shows; you give it from state. The onChangeText prop is called when the text changes; here you call the setter such as setName.

On every keystroke this flow runs: the user types a letter → React Native calls onChangeText with the new text → you call setName so state updates → the component re-renders → value shows the new state. This loop keeps the input always in sync with React. If you give value but no onChangeText the input cannot change; the user cannot type. If you give onChangeText but no value the input still works but you do not control it.

Practice Write a controlled TextInput

Write a NameForm component. Start name state as an empty string with useState. Return <TextInput value={name} onChangeText={setName} placeholder="Name" />.

Starter code

App.js
// Import useState
// Import TextInput from react-native

function NameForm() {
  // Start name state as an empty string

  return null;
}

Sample solution

App.js
import { useState } from "react";
import { TextInput } from "react-native";

function NameForm() {
  const [name, setName] = useState("");
  return (
    <TextInput
      value={name}
      onChangeText={setName}
      placeholder="Name"
    />
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How do you write a controlled TextInput?

App.js
const [name, setName] = useState("");
  • <TextInput value={name} />
  • <TextInput value={name} onChangeText={setName} /> Correct answer
  • <TextInput onChangeText={setName} />
  • <TextInput defaultValue={name} />

Explanation: value and onChangeText together make a controlled input.

2 Write the value prop

Question
<TextInput ____={name} onChangeText={setName} placeholder="Ad" />
Answer
<TextInput value={name} onChangeText={setName} placeholder="Ad" />

Explanation: The value prop is the text the input shows.

3 Match each prop to its role

Term Meaning
value Shown text
onChangeText Called on text change
useState Opens state
setName Updates state

All lessons in Intermediate