Learn to handle user input and build interactive forms in React Native applications.
Learn to handle user input and build interactive forms in React Native applications.
Master TextInput and Touchable components for handling user input and touch interactions in React Native applications
Content by: Pratik Keshvala
React Native Developer
TextInput is the fundamental component for text input in React Native. It provides a text input field that users can type into, with extensive customization options for styling and behavior.
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from 'react-native';
const InputForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
});
const handleInputChange = (field: string, value: string) => {
setFormData(prev => ({
...prev,
[field]: value
}));
};
const handleSubmit = () => {
if (!formData.name || !formData.email || !formData.password) {
Alert.alert('Error', 'Please fill in all fields');
return;
}
Alert.alert('Success', 'Form submitted successfully!');
};
return (
<View style={styles.container}>
<Text style={styles.title}>User Registration</Text>
<View style={styles.inputContainer}>
<Text style={styles.label}>Name</Text>
<TextInput
style={styles.input}
value={formData.name}
onChangeText={(value) => handleInputChange('name', value)}
placeholder="Enter your name"
autoCapitalize="words"
/>
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Email</Text>
<TextInput
style={styles.input}
value={formData.email}
onChangeText={(value) => handleInputChange('email', value)}
placeholder="Enter your email"
keyboardType="email-address"
autoCapitalize="none"
/>
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Password</Text>
<TextInput
style={styles.input}
value={formData.password}
onChangeText={(value) => handleInputChange('password', value)}
placeholder="Enter your password"
secureTextEntry
/>
</View>
<TouchableOpacity style={styles.button} onPress={handleSubmit}>
<Text style={styles.buttonText}>Submit</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
inputContainer: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: '500',
marginBottom: 8,
color: '#333',
},
input: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 12,
fontSize: 16,
backgroundColor: 'white',
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
marginTop: 20,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});
export default InputForm;Test your understanding of this topic:
Learn to implement form validation, error handling, and form state management in React Native applications
Content by: Pratik Keshvala
React Native Developer
Use React hooks like useState and useReducer to manage form state. Consider using libraries like Formik or React Hook Form for complex forms with validation.
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from 'react-native';
const ValidatedForm = () => {
const [formData, setFormData] = useState({
email: '',
password: '',
confirmPassword: '',
});
const [errors, setErrors] = useState({});
const validateEmail = (email: string) => {
const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
return emailRegex.test(email);
};
const validatePassword = (password: string) => {
return password.length >= 8;
};
const validateForm = () => {
const newErrors = {};
if (!formData.email) {
newErrors.email = 'Email is required';
} else if (!validateEmail(formData.email)) {
newErrors.email = 'Please enter a valid email';
}
if (!formData.password) {
newErrors.password = 'Password is required';
} else if (!validatePassword(formData.password)) {
newErrors.password = 'Password must be at least 8 characters';
}
if (formData.password !== formData.confirmPassword) {
newErrors.confirmPassword = 'Passwords do not match';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleInputChange = (field: string, value: string) => {
setFormData(prev => ({
...prev,
[field]: value
}));
// Clear error when user starts typing
if (errors[field]) {
setErrors(prev => ({
...prev,
[field]: ''
}));
}
};
const handleSubmit = () => {
if (validateForm()) {
Alert.alert('Success', 'Form is valid!');
}
};
return (
<View style={styles.container}>
<Text style={styles.title}>Validated Form</Text>
<View style={styles.inputContainer}>
<Text style={styles.label}>Email</Text>
<TextInput
style={[styles.input, errors.email && styles.inputError]}
value={formData.email}
onChangeText={(value) => handleInputChange('email', value)}
placeholder="Enter your email"
keyboardType="email-address"
autoCapitalize="none"
/>
{errors.email && <Text style={styles.errorText}>{errors.email}</Text>}
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Password</Text>
<TextInput
style={[styles.input, errors.password && styles.inputError]}
value={formData.password}
onChangeText={(value) => handleInputChange('password', value)}
placeholder="Enter your password"
secureTextEntry
/>
{errors.password && <Text style={styles.errorText}>{errors.password}</Text>}
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Confirm Password</Text>
<TextInput
style={[styles.input, errors.confirmPassword && styles.inputError]}
value={formData.confirmPassword}
onChangeText={(value) => handleInputChange('confirmPassword', value)}
placeholder="Confirm your password"
secureTextEntry
/>
{errors.confirmPassword && <Text style={styles.errorText}>{errors.confirmPassword}</Text>}
</View>
<TouchableOpacity style={styles.button} onPress={handleSubmit}>
<Text style={styles.buttonText}>Submit</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
inputContainer: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: '500',
marginBottom: 8,
color: '#333',
},
input: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 12,
fontSize: 16,
backgroundColor: 'white',
},
inputError: {
borderColor: '#f44336',
},
errorText: {
color: '#f44336',
fontSize: 14,
marginTop: 4,
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
marginTop: 20,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});
export default ValidatedForm;Test your understanding of this topic:
Learn to handle keyboard interactions, avoid keyboard overlap, and improve user experience when working with text inputs
Content by: Pratik Keshvala
React Native Developer
KeyboardAvoidingView automatically adjusts its height, position, or bottom padding based on the keyboard height to remain visible while the virtual keyboard is displayed.
import React, { useState } from 'react';
import {
View,
Text,
TextInput,
TouchableWithoutFeedback,
Keyboard,
KeyboardAvoidingView,
Platform,
ScrollView,
StyleSheet
} from 'react-native';
const KeyboardManagement = () => {
const [keyboardHeight, setKeyboardHeight] = useState(0);
const dismissKeyboard = () => {
Keyboard.dismiss();
};
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<TouchableWithoutFeedback onPress={dismissKeyboard}>
<View style={styles.content}>
<Text style={styles.title}>Keyboard Management</Text>
<ScrollView
contentContainerStyle={styles.scrollContent}
keyboardShouldPersistTaps="handled"
>
<View style={styles.inputContainer}>
<Text style={styles.label}>First Name</Text>
<TextInput
style={styles.input}
placeholder="Enter first name"
returnKeyType="next"
/>
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Last Name</Text>
<TextInput
style={styles.input}
placeholder="Enter last name"
returnKeyType="next"
/>
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Email</Text>
<TextInput
style={styles.input}
placeholder="Enter email"
keyboardType="email-address"
returnKeyType="next"
/>
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Message</Text>
<TextInput
style={[styles.input, styles.multilineInput]}
placeholder="Enter your message"
multiline
numberOfLines={4}
returnKeyType="done"
onSubmitEditing={dismissKeyboard}
/>
</View>
</ScrollView>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5f5f5',
},
content: {
flex: 1,
},
scrollContent: {
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
inputContainer: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: '500',
marginBottom: 8,
color: '#333',
},
input: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 12,
fontSize: 16,
backgroundColor: 'white',
},
multilineInput: {
height: 100,
textAlignVertical: 'top',
},
});
export default KeyboardManagement;Test your understanding of this topic:
Learn to use Picker and DatePicker components for selecting values from predefined options and choosing dates in React Native applications
Content by: Pratik Keshvala
React Native Developer
Picker is used to select a single value from a set of options. It renders a dropdown on Android and a wheel picker on iOS. For more advanced pickers, consider using community libraries like react-native-picker-select.
DatePicker allows users to select dates and times. The built-in DatePickerIOS is iOS-only, so for cross-platform date picking, use libraries like @react-native-community/datetimepicker.
import React, { useState } from 'react';
import {
View,
Text,
Picker,
TouchableOpacity,
StyleSheet,
Platform,
Alert
} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
const PickerExample = () => {
const [selectedCountry, setSelectedCountry] = useState('us');
const [selectedDate, setSelectedDate] = useState(new Date());
const [showDatePicker, setShowDatePicker] = useState(false);
const countries = [
{ label: 'United States', value: 'us' },
{ label: 'Canada', value: 'ca' },
{ label: 'United Kingdom', value: 'uk' },
{ label: 'Germany', value: 'de' },
{ label: 'France', value: 'fr' },
{ label: 'Japan', value: 'jp' },
];
const handleDateChange = (event: any, selectedDate?: Date) => {
setShowDatePicker(Platform.OS === 'ios');
if (selectedDate) {
setSelectedDate(selectedDate);
}
};
const showDatePickerModal = () => {
setShowDatePicker(true);
};
const handleSubmit = () => {
Alert.alert(
'Selection',
`Country: ${countries.find(c => c.value === selectedCountry)?.label}\nDate: ${selectedDate.toLocaleDateString()}`
);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Picker & DatePicker</Text>
<View style={styles.inputContainer}>
<Text style={styles.label}>Select Country</Text>
<View style={styles.pickerContainer}>
<Picker
selectedValue={selectedCountry}
onValueChange={(itemValue) => setSelectedCountry(itemValue)}
style={styles.picker}
>
{countries.map((country) => (
<Picker.Item
key={country.value}
label={country.label}
value={country.value}
/>
))}
</Picker>
</View>
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Select Date</Text>
<TouchableOpacity style={styles.dateButton} onPress={showDatePickerModal}>
<Text style={styles.dateButtonText}>
{selectedDate.toLocaleDateString()}
</Text>
</TouchableOpacity>
</View>
{showDatePicker && (
<DateTimePicker
value={selectedDate}
mode="date"
display={Platform.OS === 'ios' ? 'spinner' : 'default'}
onChange={handleDateChange}
/>
)}
<TouchableOpacity style={styles.button} onPress={handleSubmit}>
<Text style={styles.buttonText}>Submit Selection</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
inputContainer: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: '500',
marginBottom: 8,
color: '#333',
},
pickerContainer: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
backgroundColor: 'white',
},
picker: {
height: 50,
},
dateButton: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 12,
backgroundColor: 'white',
},
dateButtonText: {
fontSize: 16,
color: '#333',
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
marginTop: 20,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});
export default PickerExample;Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 4