Form events
- React Native course
- Beginner
- Lesson 81/116
- 5 min
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.
Practice 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.
Starter code
import { useState } from 'react';
import { TextInput } from 'react-native';
// write the login form hereSample solution
function App() {
const [email, setEmail] = useState('');
return (
<TextInput
value={email}
onChangeText={setEmail}
onSubmitEditing={() => console.log(email)}
/>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add onChangeText
import { TextInput } from 'react-native';
import { useState } from 'react';
function App() {
const [text, setText] = useState('');
return (
<TextInput
____={setText}
value={text}
/>
);
}
import { TextInput } from 'react-native';
import { useState } from 'react';
function App() {
const [text, setText] = useState('');
return (
<TextInput
onChangeText={setText}
value={text}
/>
);
}
Explanation: onChangeText fires on each keypress.
2 Match the form events
| Term | Meaning |
|---|---|
onChangeText |
On each keypress |
onSubmitEditing |
On the submit key |
value |
Current text |
setText |
Updates the text |
3 What fires on each keypress?
- onSubmitEditing
- onLayout
- onLongPress
- onChangeText Correct answer
Explanation: onChangeText gives the new text on each keypress.