Introduction
Form handling lets apps collect information users type in. This helps apps know what users want or need.
Form handling lets apps collect information users type in. This helps apps know what users want or need.
const [value, setValue] = useState(''); <TextInput value={value} onChangeText={text => setValue(text)} placeholder="Type here" />
const [name, setName] = useState(''); <TextInput value={name} onChangeText={text => setName(text)} placeholder="Enter your name" />
const [email, setEmail] = useState(''); <TextInput value={email} onChangeText={text => setEmail(text)} placeholder="Enter your email" keyboardType="email-address" />
This app shows a text input where the user types their favorite color. The typed text appears below in real time.
import React, { useState } from 'react'; import { View, TextInput, Text, StyleSheet } from 'react-native'; export default function App() { const [input, setInput] = useState(''); return ( <View style={styles.container}> <Text style={styles.label}>Enter your favorite color:</Text> <TextInput style={styles.input} value={input} onChangeText={text => setInput(text)} placeholder="Type color here" accessibilityLabel="Favorite color input" /> <Text style={styles.output}>You typed: {input}</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', padding: 20, backgroundColor: '#fff' }, label: { fontSize: 18, marginBottom: 10 }, input: { borderWidth: 1, borderColor: '#888', padding: 10, fontSize: 16, borderRadius: 5 }, output: { marginTop: 20, fontSize: 18, color: '#333' } });
Always keep the input value in state to capture user data.
Use accessibilityLabel for screen readers to help users with disabilities.
Update the UI to show what the user typed for better feedback.
Form handling captures what users type so apps can use that data.
Use state and TextInput in React Native to handle forms.
Show typed data back to users for clear interaction.
name when user types in a TextInput?onChangeText to capture text changes.setName is called with the new text value.onChangeText={(text) => setName(text)} -> Option Dconst [text, setText] = useState('');
return (
<>
You typed: {text}
</>
);setText to update text to 'Hello'.Text component shows 'You typed: ' plus the current text value.const [email, setEmail] = useState('');
return (
);email.setEmail to onChangeText to update the state.onChangeText should be a function, not a state variable -> Option Cusername and password, and show a message only when both are filled. Which approach correctly handles this in React Native?
const [form, setForm] = useState({username: '', password: ''});
// What should onChangeText for username be?
// And how to check if both fields are filled?setForm({...form, username: text}).form.username and form.password are truthy (not empty strings).onChangeText={text => setForm({...form, username: text})} and check form.username && form.password -> Option BPass the test and this pattern moves unknown