Skip to the workspace
Pebellslearn by building
Core Components  ›  Lesson

TextInput

Text Input 12 minA controlled TextInput shows a value from state and reports every change as a string through onChangeText, with props to choose the keyboard and handle submission.

react native / TextInput

Explore each scene at your own pace.

01 · The rule

The rule

TextInput

Sprout's "Add plant" screen asks for a name and a watering interval in days. The user types, you store what they type, and a Save button uses it. On a phone that means choosing the right keyboard too. The component is TextInput.

The rule

Value in, onChangeText out, and pick the right keyboard.

A TextInput is usually controlled: its text lives in state, value shows it, and onChangeText updates it.

const [name, setName] = useState('');
const [days, setDays] = useState('');

<TextInput
  value={name}
  onChangeText={setName}
  placeholder="Plant name"
/>
<TextInput
  value={days}
  onChangeText={setDays}
  keyboardType="numeric"
  placeholder="Water every … days"
/>
  • onChangeText receives the new text as a plain string. There is no event.target.value to dig out as on the web.
  • keyboardType picks the on-screen keyboard: 'default', 'numeric', 'email-address', 'phone-pad' and more. A number field with the full keyboard annoys users.
  • secureTextEntry hides the characters, for passwords.
  • multiline allows several lines, for plant notes.
  • onSubmitEditing runs when the user presses the keyboard's return key, and returnKeyType="done" changes that key's label.
  • autoCapitalize and autoCorrect control the keyboard's helpers. Turn them off for email addresses.

Everything typed is a string, even with the numeric keyboard. Convert before you store it: Number(days).

maxLength caps how many characters can be typed, which suits a two-digit interval. To jump from the name field to the interval field, keep a ref to the second input and call its focus() method from the first input's onSubmitEditing.

A TextInput has no visible border on iOS by default, so give it a style with borderWidth and padding or it looks invisible.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.