6.4 User Registration and Login in React Native
Chapter Overview: This chapter teaches you how to implement user authentication in React Native. You will learn to create registration and login forms, validate input, communicate with a backend API, and store JWT tokens securely for session management.
✅ Installing Required Packages
We need Axios for API requests and AsyncStorage for storing JWT tokens:
npm install axios
npm install @react-native-async-storage/async-storage
✅ Creating Registration Form
import React, { useState } from 'react';
import { View, Text, TextInput, Button, Alert } from 'react-native';
import axios from 'axios';
export default function RegisterScreen() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const registerUser = async () => {
if (!name || !email || !password) {
Alert.alert('All fields are required');
return;
}
try {
const res = await axios.post('https://yourapi.com/register', {
name, email, password
});
Alert.alert('Registration Successful!', res.data.message);
} catch (error) {
console.error(error);
Alert.alert('Registration Failed', error.response.data.message);
}
};
return (
<View style={{padding:20}}>
<TextInput placeholder="Name" value={name} onChangeText={setName} style={{borderWidth:1, marginBottom:10, padding:8}} />
<TextInput placeholder="Email" value={email} onChangeText={setEmail} keyboardType="email-address" style={{borderWidth:1, marginBottom:10, padding:8}} />
<TextInput placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry style={{borderWidth:1, marginBottom:10, padding:8}} />
<Button title="Register" onPress={registerUser} />
</View>
);
}
✅ Creating Login Form
import React, { useState } from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function LoginScreen() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const loginUser = async () => {
if (!email || !password) {
Alert.alert('Email and Password required');
return;
}
try {
const res = await axios.post('https://yourapi.com/login', { email, password });
const token = res.data.token;
await AsyncStorage.setItem('userToken', token);
Alert.alert('Login Successful!');
} catch (error) {
console.error(error);
Alert.alert('Login Failed', error.response.data.message);
}
};
return (
<View style={{padding:20}}>
<TextInput placeholder="Email" value={email} onChangeText={setEmail} style={{borderWidth:1, marginBottom:10, padding:8}} />
<TextInput placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry style={{borderWidth:1, marginBottom:10, padding:8}} />
<Button title="Login" onPress={loginUser} />
</View>
);
}
✅ Logout Function
const logoutUser = async () => {
await AsyncStorage.removeItem('userToken');
Alert.alert('Logged out successfully!');
};
✅ Tips for Authentication
- Always validate inputs on the frontend and backend.
- Store JWT tokens securely in
AsyncStorage. - Use token in headers for authenticated API requests.
- Handle API errors gracefully with alerts or toast messages.
- Combine with navigation to redirect users after login/logout.
✅ Summary
- Implemented user registration with API.
- Implemented login and stored JWT tokens for authentication.
- Used AsyncStorage to manage user session securely.
- Logout clears the token and session state.
- This setup provides a foundation for building secure user-based apps in React Native.
