TextInput and Forms
Handle user input, manage form state, and deal with the on-screen keyboard.
Learning Goals
The Core Concept
Collecting user input is essential. In React Native, the primary component for text input is <TextInput>. You manage its state using the useState hook, just like in React web. Handling forms on mobile has a unique challenge: the on-screen keyboard can cover your input fields. You can use <KeyboardAvoidingView> to automatically shift your layout when the keyboard appears.
Visual guide
React-native concept flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
import React, { useState } from 'react';
import { View, TextInput, Button, Text, StyleSheet, KeyboardAvoidingView, Platform } from 'react-native';
export default function LoginForm() {
const [email, setEmail] = useState('');
const handleLogin = () => {
alert(`Logging in with ${email}`);
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.container}
>
<Text style={styles.label}>Email Address:</Text>
<TextInput
style={styles.input}
value={email}
onChangeText={setEmail}
placeholder="Enter your email"
keyboardType="email-address"
autoCapitalize="none"
/>
<Button title="Login" onPress={handleLogin} />
</KeyboardAvoidingView>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 20, justifyContent: 'center' },
label: { marginBottom: 5, fontSize: 16 },
input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 20, borderRadius: 5 }
});Expected Output
A clean form with an email input and a login button. When typing, the appropriate email keyboard appears.
Expense Tracker
Hands-on practice task
The Challenge
Build a form to add a new expense (amount, description) to a list.
Helpful Hints
- •Create two TextInputs and a Button.
- •Store the expense list in state.
- •When the button is pressed, append the new expense to the state array and clear the inputs.
Quick Knowledge Check
How do I dismiss the keyboard when tapping outside?
Continue Learning
Next steps after this lesson
Build a form to add a new expense (amount, description) to a list.
Supercharge your career workflows!
Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.