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"
/>onChangeTextreceives the new text as a plain string. There is noevent.target.valueto dig out as on the web.keyboardTypepicks the on-screen keyboard:'default','numeric','email-address','phone-pad'and more. A number field with the full keyboard annoys users.secureTextEntryhides the characters, for passwords.multilineallows several lines, for plant notes.onSubmitEditingruns when the user presses the keyboard's return key, andreturnKeyType="done"changes that key's label.autoCapitalizeandautoCorrectcontrol 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.
The shortcut
For each field, answer three questions: where does its value live, what keyboard does it need, and what type do I need to store? Then write the props straight from the answers.
Where does the value live?
In state:
daysandsetDays. Sovalue={days}andonChangeText={setDays}.
Drills
Answer fast — trust the rule.
What does onChangeText pass to its handler?
Which prop shows a keyboard with only digits for the interval field?
The user types 7 in the numeric field. What is stored in days?
Which prop hides characters in a password field?
Which prop runs save when the user presses the keyboard's return key?
Remember
- Value in,
onChangeTextout, and pick the right keyboard. - Three questions: where the value lives, which keyboard, which type to store.
- Trap: input is always a string, even from a numeric keyboard.
