CodeBlanks Logo Icon CodeBlanks

Controlled input

Learn controlled input and state.

Controlled input

In React Native a controlled input is a TextInput whose value prop comes from a state and whose changes update that same state via onChangeText. So value={name} reads the current text from state, and onChangeText={setName} writes every keystroke back to state.

In this pattern data flows from a single source: the state. The display is always a reflection of the state. This builds a consistent structure for validation and synchronization. In this lesson we will see how to set up a controlled TextInput.

Value and state flow

The controlled pattern is set up like this: first define the state with const [name, setName] = useState("");. Then bind both props with <TextInput value={name} onChangeText={setName} />.

The flow: when the user types, onChangeText calls setName, the state updates, the component re-renders, and value={name} shows the latest text. If you omit the value prop, onChangeText still fires but the field stays uncontrolled; the value is not held by you.

Practice Set up a controlled TextInput

Import useState from react and TextInput from react-native. Create a name state (initial empty string). Make the <TextInput> controlled: include both value={name} and onChangeText={setName} props.

Starter code

App.js
// Import useState and TextInput
// Create a name state
function App() {
  return null;
}

Sample solution

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

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

Questions and answers

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

1 What does controlled input mean?

App.js
<TextInput value={name} onChangeText={setName} />
  • Value comes from state Correct answer
  • It is read-only
  • No state is used
  • Value stays fixed

Explanation: In a controlled input the value comes from a state.

2 Match the controlled flow

Term Meaning
User types onChangeText fires
setName Updates state
Re-render value refreshes
value={name} Reads from state

3 The value prop

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

Explanation: The value prop reads the current text from state in the controlled pattern.

All lessons in Beginner