onChangeText
- React Native course
- Beginner
- Lesson 25/116
- 5 min
Learn text changes with onChangeText.
onChangeText
Whenever the user types in a TextInput the text changes, and React Native reports this change through the onChangeText prop. onChangeText takes a function; the function's first argument is the new text.
Example: <TextInput onChangeText={(text) => console.log(text)} />. The arrow function is called on every keystroke and the text argument carries the current value. This is the standard way to observe text changes in React Native.
The handler function
onChangeText usually receives an arrow function or a reference to a function defined in the component. First define the function, then bind it: function handleText(text) { setText(text); } and <TextInput onChangeText={handleText} />.
Do not call the function with parentheses; that calls it once during render and binds the result. The correct form is a reference: onChangeText={handleText}. If you need to pass extra arguments, wrap it in an arrow: onChangeText={(t) => handleText(id, t)}.
Practice TextInput and onChangeText
Import useState from react and TextInput from react-native. Inside App, create a text state (initial empty string). Bind setText to the onChangeText prop of <TextInput.
Starter code
// Import useState and TextInput
// Create a text state
function App() {
return null;
}Sample solution
import { useState } from "react";
import { TextInput, View } from "react-native";
function App() {
const [text, setText] = useState("");
return (
<View>
<TextInput onChangeText={setText} value={text} />
</View>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The onChangeText prop
<TextInput ____={(text) => setText(text)} />
<TextInput onChangeText={(text) => setText(text)} />
Explanation: onChangeText passes the new text to the function.
2 What is the first parameter of the onChangeText function?
<TextInput onChangeText={(text) => {}} />- Event object
- DOM element
- Previous text
- New text Correct answer
Explanation: The first parameter is the new text the user typed.
3 Match the onChangeText pieces
| Term | Meaning |
|---|---|
onChangeText |
Called on text change |
text |
New text parameter |
useState |
Creates state |
setText |
Updates state |