React Native
Form events
Learn form submission and validation events.
Intro to form events
The most common event in forms is onChangeText. The TextInput component fires it as the user types. Each keypress gives you the new text.
Example: <TextInput onChangeText={'{setText}'}/>. Here setText is the state setter. Each letter the user types updates state and refreshes the displayed text.
For form submission there is the onSubmitEditing event. It fires when the user presses the keyboard's submit key. Example: onSubmitEditing={'{() => save()}'}. This is ideal for submitting a form with Enter.
Form submission
To catch a form submission you use onSubmitEditing. It fires when the user presses the keyboard's submit key; this is ideal for saving the form.
Example: <TextInput onSubmitEditing={'{() => save(text)}'} />. Here save is the function that processes the form. When the submit key is pressed, it is called with the text state.
For validation, check the state. For example, show an error if the email is empty. This kind of logic goes in the submit handler; not on every keypress.
Exercise A simple login form
Write an App component. Define email with useState(''). Give the <TextInput> tag value={'{email}'}, onChangeText={'{setEmail}'} and onSubmitEditing={'{() => console.log(email)}'}. Export the App function.
Show example solution
function App() {
const [email, setEmail] = useState('');
return (
<TextInput
value={email}
onChangeText={setEmail}
onSubmitEditing={() => console.log(email)}
/>
);
}
export default App;
Test yourself
-
Add onChangeText
import { TextInput } from 'react-native';
import { useState } from 'react';
function App() {
const [text, setText] = useState('');
return (
<TextInput
____={setText}
value={text}
/>
);
}
Show answer
import { TextInput } from 'react-native';
import { useState } from 'react';
function App() {
const [text, setText] = useState('');
return (
<TextInput
onChangeText={setText}
value={text}
/>
);
}
-
Match the form events
- onChangeText
- On each keypress
- onSubmitEditing
- On the submit key
- value
- Current text
- setText
- Updates the text
-
What fires on each keypress?
- onSubmitEditing
- onLayout
- onLongPress
- onChangeText
Show answer
onChangeText — onChangeText gives the new text on each keypress.
Next lesson: Summary - Events