Submit
- React Native course
- Intermediate
- Lesson 33/116
- 5 min
Learn form submit and onSubmit.
Form submission
A form is submitted after the user enters the data. In React Native submission is usually bound to a Button's onPress. In the submit handler you run validation and, if there is no error, you process the data.
Example: function handleSubmit() { if (!validate()) return; sendToServer(form); }. If validate returns false you exit early with return and submission stops. If validation passes the data is sent through a function such as sendToServer. You bind it to the button with onPress={handleSubmit}. The onSubmit event from the web does not exist in React Native; instead you use onPress. It is also common to disable the button during submission to prevent double sends.
Early return for validation
The first line of the submit handler is usually validation. If validation fails you exit early with return. This prevents the rest of the submission from running.
Example: function handleSubmit() { if (!form.email.includes("@")) { setErrors({ email: "Invalid" }); return; } console.log(form); }. If the email is invalid the error is set and the function exits; console.log does not run. This pattern makes the code readable; you get a flat flow instead of deep nested if blocks. You can run several checks in a row; each one exits early if it fails. This pattern is called a guard clause. Early return clarifies the function's purpose.
Practice Add form submission
Write a SignupForm component. Start email state with useState. Write a handleSubmit function: if not email.includes("@") exit with return. If it passes call console.log(email). Bind it to the button with onPress={handleSubmit}.
Starter code
// Import useState and Button, TextInput
function SignupForm() {
// Start email state (empty string)
// handleSubmit function: email check, otherwise log
return null;
}Sample solution
import { useState } from "react";
import { Button, TextInput } from "react-native";
function SignupForm() {
const [email, setEmail] = useState("");
function handleSubmit() {
if (!email.includes("@")) return;
console.log(email);
}
return (
<>
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Email"
/>
<Button onPress={handleSubmit} title="Submit" />
</>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which prop handles form submission in React Native?
<Button onPress={handleSubmit} title="Gönder" />- onPress Correct answer
- onClick
- onSubmitForm
- onSubmit
Explanation: In React Native button press is caught with onPress.
2 Bind the submit handler to the button
<Button onPress={____} title="Gönder" />
<Button onPress={handleSubmit} title="Gönder" />
Explanation: onPress={handleSubmit} binds it to the button.
3 Match the concept to its role
| Term | Meaning |
|---|---|
handleSubmit |
Submit handler |
onPress |
Binds to button |
return |
Early exit |
validate |
Rule check |