Creating a flight booking mobile app using React Native is a great idea. Here are some essential functionalities and features you should consider implementing:
Core Features
-
User Authentication
- Sign up
- Login
- Social media login (Google, Facebook, etc.)
- Password recovery
-
Flight Search
- Search flights by destination, date, and other filters
- Advanced search options (e.g., multi-city, flexible dates)
-
Flight Details
- Display flight options with details like time, duration, airline, stops, etc.
- Price comparison
- Baggage policy information
-
Booking and Payment
- Select seats
- Add-ons (e.g., extra baggage, meals)
- Payment gateway integration (credit/debit card, PayPal, etc.)
- Payment history and receipts
-
User Profile
- View and edit profile details
- Save payment methods
- View booking history
- Manage saved preferences (e.g., preferred airlines, seating preferences)
-
Notifications
- Push notifications for booking confirmations, flight status updates, special offers, etc.
- Email notifications
-
Flight Status Tracking
- Real-time flight status updates
- Notifications for delays or cancellations
-
Customer Support
- In-app chat support
- Contact information for customer service
Additional Features
-
Loyalty Programs
- Integration with frequent flyer programs
- Rewards tracking
-
Price Alerts
- Set alerts for price drops on specific routes
-
In-App Reviews and Ratings
- Allow users to rate their flight experience
- View ratings and reviews of different airlines
-
Multi-language Support
- Localization for different regions
-
Currency Converter
- Display prices in different currencies based on user preference
-
Weather Forecast
- Show weather information for the destination city
-
Offline Access
- Access booking details and boarding pass offline
Technical Considerations
-
API Integration
- Integrate with flight data providers (e.g., Amadeus, Skyscanner)
- Payment gateway APIs
-
State Management
- Use Redux or Context API for managing global state
-
Navigation
- Use React Navigation for handling screen transitions
-
Storage
- Secure storage for sensitive data (e.g., payment details)
- Local storage for caching search results
-
Testing
- Unit testing (e.g., using Jest)
- End-to-end testing (e.g., using Detox)
-
Performance Optimization
- Optimize images and assets
- Code splitting and lazy loading
Development Tools
- React Native CLI: For initializing and managing the project.
- Expo: Optional, but can be used for quick prototyping and certain built-in functionalities.
- VS Code: Popular code editor with extensions for React Native development.
- Postman: For testing APIs.
- Git: For version control.
Project Setup
- Initialize Project
npx react-native init FlightBookingApp
- Install Dependencies
npm install @react-navigation/native @react-navigation/stack redux react-redux axios
# Additional dependencies based on features
- Folder Structure
FlightBookingApp/
├── android/
├── ios/
├── src/
│ ├── components/
│ ├── screens/
│ ├── navigation/
│ ├── redux/
│ ├── services/
│ ├── utils/
│ └── assets/
├── App.js
└── package.json
This should give you a solid foundation to start building your flight booking app.
Here's a basic implementation of user authentication features (Sign up, Login, Social Media Login, and Password Recovery) using React Native and Firebase. Firebase provides easy-to-use authentication services that integrate well with React Native.
Step 1: Set Up Firebase
-
Create a Firebase Project
- Go to Firebase Console
- Create a new project
- Add an Android/iOS app to your project and follow the setup instructions to get your configuration file (google-services.json for Android and GoogleService-Info.plist for iOS)
Install Firebase in Your React Native Project
npm install @react-native-firebase/app @react-native-firebase/auth
-
Configure Firebase
- For Android: Place
google-services.json
inandroid/app/
- For iOS: Place
GoogleService-Info.plist
in theios/
directory
- For Android: Place
Step 2: Implement Authentication
Firebase Configuration
Create a firebaseConfig.js
file to initialize Firebase:
// src/firebaseConfig.js
import { firebase } from '@react-native-firebase/app';
import '@react-native-firebase/auth';
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export default firebase;
Sign Up
Create a SignUpScreen.js
for user registration:
// src/screens/SignUpScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import firebase from '../firebaseConfig';
const SignUpScreen = ({ navigation }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSignUp = async () => {
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
navigation.navigate('Login');
} catch (error) {
setError(error.message);
}
};
return (
<View>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
{error ? <Text>{error}</Text> : null}
<Button title="Sign Up" onPress={handleSignUp} />
</View>
);
};
export default SignUpScreen;
Login
Create a LoginScreen.js
for user login:
// src/screens/LoginScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import firebase from '../firebaseConfig';
const LoginScreen = ({ navigation }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleLogin = async () => {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
navigation.navigate('Home');
} catch (error) {
setError(error.message);
}
};
return (
<View>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
{error ? <Text>{error}</Text> : null}
<Button title="Login" onPress={handleLogin} />
</View>
);
};
export default LoginScreen;
Password Recovery
Create a PasswordRecoveryScreen.js
for password recovery:
// src/screens/PasswordRecoveryScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import firebase from '../firebaseConfig';
const PasswordRecoveryScreen = ({ navigation }) => {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const handlePasswordReset = async () => {
try {
await firebase.auth().sendPasswordResetEmail(email);
setMessage('Password reset email sent!');
} catch (error) {
setMessage(error.message);
}
};
return (
<View>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
/>
<Button title="Reset Password" onPress={handlePasswordReset} />
{message ? <Text>{message}</Text> : null}
</View>
);
};
export default PasswordRecoveryScreen;
Social Media Login
Set up social media login using OAuth. Here, I'll demonstrate Google login.
- Install Required Packages
npm install @react-native-google-signin/google-signin
- Configure Google Sign-In
Create a GoogleSignInConfig.js
file to configure Google Sign-In:
// src/GoogleSignInConfig.js
import { GoogleSignin } from '@react-native-google-signin/google-signin';
GoogleSignin.configure({
webClientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', // From Firebase Console
offlineAccess: false,
});
export default GoogleSignin;
- Google Login Implementation
Update your LoginScreen.js
to include Google login:
// src/screens/LoginScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import firebase from '../firebaseConfig';
import GoogleSignInConfig from '../GoogleSignInConfig';
import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';
const LoginScreen = ({ navigation }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleLogin = async () => {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
navigation.navigate('Home');
} catch (error) {
setError(error.message);
}
};
const handleGoogleLogin = async () => {
try {
await GoogleSignin.hasPlayServices();
const { idToken } = await GoogleSignin.signIn();
const googleCredential = firebase.auth.GoogleAuthProvider.credential(idToken);
await firebase.auth().signInWithCredential(googleCredential);
navigation.navigate('Home');
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
setError('User cancelled the login flow');
} else if (error.code === statusCodes.IN_PROGRESS) {
setError('Signin in progress');
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
setError('Play services not available or outdated');
} else {
setError(error.message);
}
}
};
return (
<View>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
{error ? <Text>{error}</Text> : null}
<Button title="Login" onPress={handleLogin} />
<Button title="Login with Google" onPress={handleGoogleLogin} />
</View>
);
};
export default LoginScreen;
Navigation Setup
Make sure you have React Navigation set up to handle screen transitions. Here's an example App.js
:
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import SignUpScreen from './src/screens/SignUpScreen';
import LoginScreen from './src/screens/LoginScreen';
import PasswordRecoveryScreen from './src/screens/PasswordRecoveryScreen';
import HomeScreen from './src/screens/HomeScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Login">
<Stack.Screen name="SignUp" component={SignUpScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="PasswordRecovery" component={PasswordRecoveryScreen} />
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
Final Steps
- Make sure you have set up the SHA-1 key for Android in the Firebase Console for Google Sign-In.
- Configure your iOS and Android projects according to Firebase and Google Sign-In documentation.
This is a basic implementation of user authentication using Firebase in a React Native app. You can expand upon this by adding more features and improving error handling and user experience.
Implementing flight search and flight details functionalities requires integrating with a flight data provider API. For this example, we'll use a hypothetical flight API. You can adapt this to any real API by following their documentation.
Step 1: Set Up API Integration
Create a service to handle API requests.
FlightService.js
// src/services/FlightService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.example.com'; // Replace with actual API URL
const searchFlights = async (params) => {
try {
const response = await axios.get(`${API_BASE_URL}/flights/search`, { params });
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { searchFlights };
Step 2: Implement Flight Search
Create a screen to handle flight search.
FlightSearchScreen.js
// src/screens/FlightSearchScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text, FlatList, TouchableOpacity } from 'react-native';
import { searchFlights } from '../services/FlightService';
const FlightSearchScreen = ({ navigation }) => {
const [from, setFrom] = useState('');
const [to, setTo] = useState('');
const [date, setDate] = useState('');
const [flights, setFlights] = useState([]);
const [error, setError] = useState('');
const handleSearch = async () => {
try {
const results = await searchFlights({ from, to, date });
setFlights(results);
} catch (error) {
setError('Error fetching flights');
}
};
const renderFlightItem = ({ item }) => (
<TouchableOpacity onPress={() => navigation.navigate('FlightDetails', { flight: item })}>
<View>
<Text>{item.airline}</Text>
<Text>{item.departure_time} - {item.arrival_time}</Text>
<Text>{item.price}</Text>
</View>
</TouchableOpacity>
);
return (
<View>
<TextInput placeholder="From" value={from} onChangeText={setFrom} />
<TextInput placeholder="To" value={to} onChangeText={setTo} />
<TextInput placeholder="Date" value={date} onChangeText={setDate} />
<Button title="Search Flights" onPress={handleSearch} />
{error ? <Text>{error}</Text> : null}
<FlatList
data={flights}
keyExtractor={(item) => item.id}
renderItem={renderFlightItem}
/>
</View>
);
};
export default FlightSearchScreen;
Step 3: Implement Flight Details
Create a screen to display flight details.
FlightDetailsScreen.js
// src/screens/FlightDetailsScreen.js
import React from 'react';
import { View, Text } from 'react-native';
const FlightDetailsScreen = ({ route }) => {
const { flight } = route.params;
return (
<View>
<Text>Airline: {flight.airline}</Text>
<Text>Departure Time: {flight.departure_time}</Text>
<Text>Arrival Time: {flight.arrival_time}</Text>
<Text>Duration: {flight.duration}</Text>
<Text>Price: {flight.price}</Text>
<Text>Stops: {flight.stops}</Text>
<Text>Baggage Policy: {flight.baggage_policy}</Text>
</View>
);
};
export default FlightDetailsScreen;
Step 4: Navigation Setup
Update your App.js
to include the new screens.
App.js
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import FlightSearchScreen from './src/screens/FlightSearchScreen';
import FlightDetailsScreen from './src/screens/FlightDetailsScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="FlightSearch">
<Stack.Screen name="FlightSearch" component={FlightSearchScreen} />
<Stack.Screen name="FlightDetails" component={FlightDetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
Advanced Search Options
For advanced search options (multi-city, flexible dates), you can extend the FlightSearchScreen
to include additional input fields and logic for handling those parameters.
FlightSearchScreen.js (Extended)
// src/screens/FlightSearchScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text, FlatList, TouchableOpacity } from 'react-native';
import { searchFlights } from '../services/FlightService';
const FlightSearchScreen = ({ navigation }) => {
const [from, setFrom] = useState('');
const [to, setTo] = useState('');
const [date, setDate] = useState('');
const [multiCity, setMultiCity] = useState(false);
const [secondLegFrom, setSecondLegFrom] = useState('');
const [secondLegTo, setSecondLegTo] = useState('');
const [secondLegDate, setSecondLegDate] = useState('');
const [flights, setFlights] = useState([]);
const [error, setError] = useState('');
const handleSearch = async () => {
try {
const params = multiCity
? { from, to, date, secondLegFrom, secondLegTo, secondLegDate }
: { from, to, date };
const results = await searchFlights(params);
setFlights(results);
} catch (error) {
setError('Error fetching flights');
}
};
const renderFlightItem = ({ item }) => (
<TouchableOpacity onPress={() => navigation.navigate('FlightDetails', { flight: item })}>
<View>
<Text>{item.airline}</Text>
<Text>{item.departure_time} - {item.arrival_time}</Text>
<Text>{item.price}</Text>
</View>
</TouchableOpacity>
);
return (
<View>
<TextInput placeholder="From" value={from} onChangeText={setFrom} />
<TextInput placeholder="To" value={to} onChangeText={setTo} />
<TextInput placeholder="Date" value={date} onChangeText={setDate} />
{multiCity && (
<>
<TextInput placeholder="Second Leg From" value={secondLegFrom} onChangeText={setSecondLegFrom} />
<TextInput placeholder="Second Leg To" value={secondLegTo} onChangeText={setSecondLegTo} />
<TextInput placeholder="Second Leg Date" value={secondLegDate} onChangeText={setSecondLegDate} />
</>
)}
<Button title="Multi-City" onPress={() => setMultiCity(!multiCity)} />
<Button title="Search Flights" onPress={handleSearch} />
{error ? <Text>{error}</Text> : null}
<FlatList
data={flights}
keyExtractor={(item) => item.id}
renderItem={renderFlightItem}
/>
</View>
);
};
export default FlightSearchScreen;
This setup provides a basic structure for searching and displaying flight details in a React Native app. You can further customize it based on your specific requirements and the API documentation you are working with.
Integrating booking and payment functionality involves several steps, including seat selection, adding extras, integrating a payment gateway, and managing payment history and receipts. Here's a step-by-step guide to implement these features:
Step 1: Set Up API Integration
Create a service to handle booking-related API requests.
BookingService.js
// src/services/BookingService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.example.com'; // Replace with actual API URL
const selectSeats = async (bookingId, seats) => {
try {
const response = await axios.post(`${API_BASE_URL}/bookings/${bookingId}/seats`, { seats });
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const addAddons = async (bookingId, addons) => {
try {
const response = await axios.post(`${API_BASE_URL}/bookings/${bookingId}/addons`, { addons });
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const makePayment = async (bookingId, paymentDetails) => {
try {
const response = await axios.post(`${API_BASE_URL}/bookings/${bookingId}/payment`, { paymentDetails });
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const getPaymentHistory = async (userId) => {
try {
const response = await axios.get(`${API_BASE_URL}/users/${userId}/payments`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { selectSeats, addAddons, makePayment, getPaymentHistory };
Step 2: Implement Booking Screen
Create a screen for selecting seats and adding add-ons.
BookingScreen.js
// src/screens/BookingScreen.js
import React, { useState } from 'react';
import { View, Text, Button, FlatList, TouchableOpacity } from 'react-native';
import { selectSeats, addAddons } from '../services/BookingService';
const BookingScreen = ({ route, navigation }) => {
const { bookingId } = route.params;
const [seats, setSeats] = useState([]);
const [addons, setAddons] = useState([]);
const [error, setError] = useState('');
const handleSeatSelection = async (selectedSeats) => {
try {
const response = await selectSeats(bookingId, selectedSeats);
setSeats(response.seats);
} catch (error) {
setError('Error selecting seats');
}
};
const handleAddonsSelection = async (selectedAddons) => {
try {
const response = await addAddons(bookingId, selectedAddons);
setAddons(response.addons);
} catch (error) {
setError('Error adding addons');
}
};
const renderSeatItem = ({ item }) => (
<TouchableOpacity onPress={() => handleSeatSelection([item])}>
<View>
<Text>{item.seatNumber}</Text>
</View>
</TouchableOpacity>
);
const renderAddonItem = ({ item }) => (
<TouchableOpacity onPress={() => handleAddonsSelection([item])}>
<View>
<Text>{item.name}</Text>
</View>
</TouchableOpacity>
);
return (
<View>
<Text>Select Seats</Text>
<FlatList
data={/* Fetch seat data */}
keyExtractor={(item) => item.id}
renderItem={renderSeatItem}
/>
<Text>Select Add-ons</Text>
<FlatList
data={/* Fetch addons data */}
keyExtractor={(item) => item.id}
renderItem={renderAddonItem}
/>
{error ? <Text>{error}</Text> : null}
<Button title="Proceed to Payment" onPress={() => navigation.navigate('Payment', { bookingId })} />
</View>
);
};
export default BookingScreen;
Step 3: Implement Payment Screen
Integrate a payment gateway (e.g., Stripe or PayPal). For this example, we'll use a mock payment integration.
PaymentScreen.js
// src/screens/PaymentScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import { makePayment } from '../services/BookingService';
const PaymentScreen = ({ route, navigation }) => {
const { bookingId } = route.params;
const [cardNumber, setCardNumber] = useState('');
const [expiryDate, setExpiryDate] = useState('');
const [cvv, setCvv] = useState('');
const [error, setError] = useState('');
const handlePayment = async () => {
try {
const paymentDetails = { cardNumber, expiryDate, cvv };
await makePayment(bookingId, paymentDetails);
navigation.navigate('PaymentHistory');
} catch (error) {
setError('Error processing payment');
}
};
return (
<View>
<TextInput placeholder="Card Number" value={cardNumber} onChangeText={setCardNumber} />
<TextInput placeholder="Expiry Date" value={expiryDate} onChangeText={setExpiryDate} />
<TextInput placeholder="CVV" value={cvv} onChangeText={setCvv} secureTextEntry />
{error ? <Text>{error}</Text> : null}
<Button title="Make Payment" onPress={handlePayment} />
</View>
);
};
export default PaymentScreen;
Step 4: Implement Payment History Screen
Create a screen to display payment history.
PaymentHistoryScreen.js
// src/screens/PaymentHistoryScreen.js
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';
import { getPaymentHistory } from '../services/BookingService';
const PaymentHistoryScreen = ({ route }) => {
const { userId } = route.params;
const [payments, setPayments] = useState([]);
const [error, setError] = useState('');
useEffect(() => {
const fetchPaymentHistory = async () => {
try {
const paymentHistory = await getPaymentHistory(userId);
setPayments(paymentHistory);
} catch (error) {
setError('Error fetching payment history');
}
};
fetchPaymentHistory();
}, [userId]);
const renderPaymentItem = ({ item }) => (
<View>
<Text>Payment ID: {item.id}</Text>
<Text>Amount: {item.amount}</Text>
<Text>Date: {item.date}</Text>
</View>
);
return (
<View>
{error ? <Text>{error}</Text> : null}
<FlatList
data={payments}
keyExtractor={(item) => item.id}
renderItem={renderPaymentItem}
/>
</View>
);
};
export default PaymentHistoryScreen;
Navigation Setup
Update your App.js
to include the new screens.
App.js
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import BookingScreen from './src/screens/BookingScreen';
import PaymentScreen from './src/screens/PaymentScreen';
import PaymentHistoryScreen from './src/screens/PaymentHistoryScreen';
import FlightSearchScreen from './src/screens/FlightSearchScreen';
import FlightDetailsScreen from './src/screens/FlightDetailsScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="FlightSearch">
<Stack.Screen name="FlightSearch" component={FlightSearchScreen} />
<Stack.Screen name="FlightDetails" component={FlightDetailsScreen} />
<Stack.Screen name="Booking" component={BookingScreen} />
<Stack.Screen name="Payment" component={PaymentScreen} />
<Stack.Screen name="PaymentHistory" component={PaymentHistoryScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
This setup provides a basic structure for booking flights, selecting seats, adding add-ons, making payments, and viewing payment history in a React Native app.
Implementing user profile management and notifications involves several steps. Let's break it down into manageable parts.
User Profile Management
- View and Edit Profile Details
- Save Payment Methods
- View Booking History
- Manage Saved Preferences
Step 1: Set Up API Integration
Create a service to handle user profile-related API requests.
UserService.js
// src/services/UserService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.example.com'; // Replace with actual API URL
const getUserProfile = async (userId) => {
try {
const response = await axios.get(`${API_BASE_URL}/users/${userId}`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const updateUserProfile = async (userId, profileData) => {
try {
const response = await axios.put(`${API_BASE_URL}/users/${userId}`, profileData);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const savePaymentMethod = async (userId, paymentMethod) => {
try {
const response = await axios.post(`${API_BASE_URL}/users/${userId}/payment-methods`, paymentMethod);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const getBookingHistory = async (userId) => {
try {
const response = await axios.get(`${API_BASE_URL}/users/${userId}/bookings`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const savePreferences = async (userId, preferences) => {
try {
const response = await axios.post(`${API_BASE_URL}/users/${userId}/preferences`, preferences);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { getUserProfile, updateUserProfile, savePaymentMethod, getBookingHistory, savePreferences };
Step 2: Implement User Profile Screen
UserProfileScreen.js
// src/screens/UserProfileScreen.js
import React, { useEffect, useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import { getUserProfile, updateUserProfile, savePreferences } from '../services/UserService';
const UserProfileScreen = ({ route }) => {
const { userId } = route.params;
const [profile, setProfile] = useState({});
const [preferences, setPreferences] = useState({});
const [error, setError] = useState('');
useEffect(() => {
const fetchUserProfile = async () => {
try {
const userProfile = await getUserProfile(userId);
setProfile(userProfile);
} catch (error) {
setError('Error fetching profile');
}
};
fetchUserProfile();
}, [userId]);
const handleUpdateProfile = async () => {
try {
await updateUserProfile(userId, profile);
} catch (error) {
setError('Error updating profile');
}
};
const handleSavePreferences = async () => {
try {
await savePreferences(userId, preferences);
} catch (error) {
setError('Error saving preferences');
}
};
return (
<View>
<TextInput
placeholder="Name"
value={profile.name || ''}
onChangeText={(text) => setProfile({ ...profile, name: text })}
/>
<TextInput
placeholder="Email"
value={profile.email || ''}
onChangeText={(text) => setProfile({ ...profile, email: text })}
/>
<TextInput
placeholder="Preferred Airlines"
value={preferences.preferredAirlines || ''}
onChangeText={(text) => setPreferences({ ...preferences, preferredAirlines: text })}
/>
<TextInput
placeholder="Seating Preferences"
value={preferences.seatingPreferences || ''}
onChangeText={(text) => setPreferences({ ...preferences, seatingPreferences: text })}
/>
{error ? <Text>{error}</Text> : null}
<Button title="Update Profile" onPress={handleUpdateProfile} />
<Button title="Save Preferences" onPress={handleSavePreferences} />
</View>
);
};
export default UserProfileScreen;
Step 3: Implement Payment Methods Screen
PaymentMethodsScreen.js
// src/screens/PaymentMethodsScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import { savePaymentMethod } from '../services/UserService';
const PaymentMethodsScreen = ({ route }) => {
const { userId } = route.params;
const [cardNumber, setCardNumber] = useState('');
const [expiryDate, setExpiryDate] = useState('');
const [cvv, setCvv] = useState('');
const [error, setError] = useState('');
const handleSavePaymentMethod = async () => {
try {
const paymentMethod = { cardNumber, expiryDate, cvv };
await savePaymentMethod(userId, paymentMethod);
} catch (error) {
setError('Error saving payment method');
}
};
return (
<View>
<TextInput placeholder="Card Number" value={cardNumber} onChangeText={setCardNumber} />
<TextInput placeholder="Expiry Date" value={expiryDate} onChangeText={setExpiryDate} />
<TextInput placeholder="CVV" value={cvv} onChangeText={setCvv} secureTextEntry />
{error ? <Text>{error}</Text> : null}
<Button title="Save Payment Method" onPress={handleSavePaymentMethod} />
</View>
);
};
export default PaymentMethodsScreen;
Step 4: Implement Booking History Screen
BookingHistoryScreen.js
// src/screens/BookingHistoryScreen.js
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';
import { getBookingHistory } from '../services/UserService';
const BookingHistoryScreen = ({ route }) => {
const { userId } = route.params;
const [bookings, setBookings] = useState([]);
const [error, setError] = useState('');
useEffect(() => {
const fetchBookingHistory = async () => {
try {
const bookingHistory = await getBookingHistory(userId);
setBookings(bookingHistory);
} catch (error) {
setError('Error fetching booking history');
}
};
fetchBookingHistory();
}, [userId]);
const renderBookingItem = ({ item }) => (
<View>
<Text>Booking ID: {item.id}</Text>
<Text>Flight: {item.flightNumber}</Text>
<Text>Date: {item.date}</Text>
<Text>Amount: {item.amount}</Text>
</View>
);
return (
<View>
{error ? <Text>{error}</Text> : null}
<FlatList
data={bookings}
keyExtractor={(item) => item.id}
renderItem={renderBookingItem}
/>
</View>
);
};
export default BookingHistoryScreen;
Step 5: Implement Notifications
Implementing notifications involves setting up push notifications and email notifications.
Setup Push Notifications
Use libraries like react-native-push-notification
for push notifications.
Setup Email Notifications
Integrate with an email service provider (e.g., SendGrid) to send email notifications.
Navigation Setup
Update your App.js
to include the new screens.
App.js
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import UserProfileScreen from './src/screens/UserProfileScreen';
import PaymentMethodsScreen from './src/screens/PaymentMethodsScreen';
import BookingHistoryScreen from './src/screens/BookingHistoryScreen';
import FlightSearchScreen from './src/screens/FlightSearchScreen';
import FlightDetailsScreen from './src/screens/FlightDetailsScreen';
import BookingScreen from './src/screens/BookingScreen';
import PaymentScreen from './src/screens/PaymentScreen';
import PaymentHistoryScreen from './src/screens/PaymentHistoryScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="FlightSearch">
<Stack.Screen name="FlightSearch" component={FlightSearchScreen} />
<Stack.Screen name="FlightDetails" component={FlightDetailsScreen} />
<Stack.Screen name="Booking" component={BookingScreen} />
<Stack.Screen name="Payment" component={PaymentScreen} />
<Stack.Screen name="PaymentHistory" component={PaymentHistoryScreen} />
<Stack.Screen name="UserProfile" component={UserProfileScreen} />
<Stack.Screen name="PaymentMethods" component={PaymentMethodsScreen} />
<Stack.Screen name="BookingHistory" component={BookingHistoryScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
This setup provides a basic structure for managing user profiles, payment methods, booking history, and notifications in a React Native app.
To implement flight status tracking and customer support in your React Native app, you'll need to integrate APIs for real-time flight status updates and a service for in-app chat support. Let's go through the steps to implement these features.
Flight Status Tracking
Step 1: Set Up API Integration
Create a service to handle flight status-related API requests.
FlightStatusService.js
// src/services/FlightStatusService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.flightstatus.com'; // Replace with actual API URL
const getFlightStatus = async (flightNumber) => {
try {
const response = await axios.get(`${API_BASE_URL}/flights/${flightNumber}/status`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { getFlightStatus };
Step 2: Implement Flight Status Screen
Create a screen to display real-time flight status updates.
FlightStatusScreen.js
// src/screens/FlightStatusScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import { getFlightStatus } from '../services/FlightStatusService';
const FlightStatusScreen = () => {
const [flightNumber, setFlightNumber] = useState('');
const [flightStatus, setFlightStatus] = useState(null);
const [error, setError] = useState('');
const handleCheckStatus = async () => {
try {
const status = await getFlightStatus(flightNumber);
setFlightStatus(status);
} catch (error) {
setError('Error fetching flight status');
}
};
return (
<View>
<TextInput
placeholder="Enter Flight Number"
value={flightNumber}
onChangeText={setFlightNumber}
/>
<Button title="Check Status" onPress={handleCheckStatus} />
{error ? <Text>{error}</Text> : null}
{flightStatus ? (
<View>
<Text>Flight Number: {flightStatus.flightNumber}</Text>
<Text>Status: {flightStatus.status}</Text>
<Text>Departure Time: {flightStatus.departureTime}</Text>
<Text>Arrival Time: {flightStatus.arrivalTime}</Text>
</View>
) : null}
</View>
);
};
export default FlightStatusScreen;
Notifications for Flight Status
Use a service like Firebase Cloud Messaging (FCM) for push notifications. This requires setting up FCM in your React Native app.
Setting Up FCM (Brief Overview)
- Install the necessary packages:
npm install @react-native-firebase/app @react-native-firebase/messaging
Configure Firebase:
Follow the instructions on the React Native Firebase documentation to set up Firebase in your app.Handle Notifications:
// App.js
import messaging from '@react-native-firebase/messaging';
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
return unsubscribe;
}, []);
Customer Support
Step 1: Integrate In-App Chat Support
Use a service like Firebase Firestore for in-app chat or a third-party service like Zendesk or Intercom.
InAppChatService.js (using Firebase Firestore)
// src/services/InAppChatService.js
import firestore from '@react-native-firebase/firestore';
const sendMessage = async (chatId, message) => {
try {
await firestore().collection('chats').doc(chatId).collection('messages').add({
text: message,
createdAt: firestore.FieldValue.serverTimestamp(),
});
} catch (error) {
console.error(error);
throw error;
}
};
const getMessages = (chatId, callback) => {
return firestore().collection('chats').doc(chatId).collection('messages')
.orderBy('createdAt', 'desc')
.onSnapshot(callback);
};
export { sendMessage, getMessages };
Step 2: Implement Chat Screen
Create a screen for in-app chat support.
ChatScreen.js
// src/screens/ChatScreen.js
import React, { useEffect, useState } from 'react';
import { View, TextInput, Button, FlatList, Text } from 'react-native';
import { sendMessage, getMessages } from '../services/InAppChatService';
const ChatScreen = ({ route }) => {
const { chatId } = route.params;
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
useEffect(() => {
const unsubscribe = getMessages(chatId, (snapshot) => {
const fetchedMessages = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
setMessages(fetchedMessages);
});
return () => unsubscribe();
}, [chatId]);
const handleSend = async () => {
try {
await sendMessage(chatId, message);
setMessage('');
} catch (error) {
console.error('Error sending message:', error);
}
};
const renderMessage = ({ item }) => (
<View>
<Text>{item.text}</Text>
<Text>{item.createdAt?.toDate().toLocaleString()}</Text>
</View>
);
return (
<View>
<FlatList
data={messages}
keyExtractor={(item) => item.id}
renderItem={renderMessage}
/>
<TextInput
placeholder="Type your message"
value={message}
onChangeText={setMessage}
/>
<Button title="Send" onPress={handleSend} />
</View>
);
};
export default ChatScreen;
Step 3: Customer Service Contact Information
CustomerServiceScreen.js
// src/screens/CustomerServiceScreen.js
import React from 'react';
import { View, Text } from 'react-native';
const CustomerServiceScreen = () => {
return (
<View>
<Text>Customer Service</Text>
<Text>Email: support@example.com</Text>
<Text>Phone: +1 (800) 123-4567</Text>
</View>
);
};
export default CustomerServiceScreen;
Navigation Setup
Update your App.js
to include the new screens.
App.js
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import UserProfileScreen from './src/screens/UserProfileScreen';
import PaymentMethodsScreen from './src/screens/PaymentMethodsScreen';
import BookingHistoryScreen from './src/screens/BookingHistoryScreen';
import FlightSearchScreen from './src/screens/FlightSearchScreen';
import FlightDetailsScreen from './src/screens/FlightDetailsScreen';
import BookingScreen from './src/screens/BookingScreen';
import PaymentScreen from './src/screens/PaymentScreen';
import PaymentHistoryScreen from './src/screens/PaymentHistoryScreen';
import FlightStatusScreen from './src/screens/FlightStatusScreen';
import ChatScreen from './src/screens/ChatScreen';
import CustomerServiceScreen from './src/screens/CustomerServiceScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="FlightSearch">
<Stack.Screen name="FlightSearch" component={FlightSearchScreen} />
<Stack.Screen name="FlightDetails" component={FlightDetailsScreen} />
<Stack.Screen name="Booking" component={BookingScreen} />
<Stack.Screen name="Payment" component={PaymentScreen} />
<Stack.Screen name="PaymentHistory" component={PaymentHistoryScreen} />
<Stack.Screen name="UserProfile" component={UserProfileScreen} />
<Stack.Screen name="PaymentMethods" component={PaymentMethodsScreen} />
<Stack.Screen name="BookingHistory" component={BookingHistoryScreen} />
<Stack.Screen name="FlightStatus" component={FlightStatusScreen} />
<Stack.Screen name="Chat" component={ChatScreen} />
<Stack.Screen name="CustomerService" component={CustomerServiceScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
This setup provides a basic structure for tracking flight status, implementing in-app chat support, and providing customer service contact information in a React Native app.
To implement loyalty programs, price alerts, and in-app reviews and ratings, you will need to integrate various APIs and set up your application structure accordingly. Let's break down each feature and provide the necessary code.
Loyalty Programs
Step 1: Set Up API Integration
Create a service to handle loyalty program-related API requests.
LoyaltyService.js
// src/services/LoyaltyService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.loyaltyprogram.com'; // Replace with actual API URL
const getLoyaltyPoints = async (userId) => {
try {
const response = await axios.get(`${API_BASE_URL}/users/${userId}/loyalty-points`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const getFrequentFlyerPrograms = async (userId) => {
try {
const response = await axios.get(`${API_BASE_URL}/users/${userId}/frequent-flyer-programs`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { getLoyaltyPoints, getFrequentFlyerPrograms };
Step 2: Implement Loyalty Program Screen
LoyaltyScreen.js
// src/screens/LoyaltyScreen.js
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { getLoyaltyPoints, getFrequentFlyerPrograms } from '../services/LoyaltyService';
const LoyaltyScreen = ({ route }) => {
const { userId } = route.params;
const [loyaltyPoints, setLoyaltyPoints] = useState(null);
const [frequentFlyerPrograms, setFrequentFlyerPrograms] = useState([]);
const [error, setError] = useState('');
useEffect(() => {
const fetchLoyaltyData = async () => {
try {
const points = await getLoyaltyPoints(userId);
setLoyaltyPoints(points);
const programs = await getFrequentFlyerPrograms(userId);
setFrequentFlyerPrograms(programs);
} catch (error) {
setError('Error fetching loyalty data');
}
};
fetchLoyaltyData();
}, [userId]);
return (
<View>
{error ? <Text>{error}</Text> : null}
{loyaltyPoints !== null && (
<View>
<Text>Loyalty Points: {loyaltyPoints.points}</Text>
</View>
)}
<View>
<Text>Frequent Flyer Programs:</Text>
{frequentFlyerPrograms.map(program => (
<View key={program.id}>
<Text>{program.name}: {program.points} points</Text>
</View>
))}
</View>
</View>
);
};
export default LoyaltyScreen;
Price Alerts
Step 1: Set Up API Integration
Create a service to handle price alert-related API requests.
PriceAlertService.js
// src/services/PriceAlertService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.pricealerts.com'; // Replace with actual API URL
const setPriceAlert = async (userId, route, price) => {
try {
const response = await axios.post(`${API_BASE_URL}/users/${userId}/price-alerts`, { route, price });
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const getPriceAlerts = async (userId) => {
try {
const response = await axios.get(`${API_BASE_URL}/users/${userId}/price-alerts`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { setPriceAlert, getPriceAlerts };
Step 2: Implement Price Alerts Screen
PriceAlertScreen.js
// src/screens/PriceAlertScreen.js
import React, { useEffect, useState } from 'react';
import { View, TextInput, Button, Text, FlatList } from 'react-native';
import { setPriceAlert, getPriceAlerts } from '../services/PriceAlertService';
const PriceAlertScreen = ({ route }) => {
const { userId } = route.params;
const [routeName, setRouteName] = useState('');
const [price, setPrice] = useState('');
const [alerts, setAlerts] = useState([]);
const [error, setError] = useState('');
const handleSetAlert = async () => {
try {
await setPriceAlert(userId, routeName, price);
setRouteName('');
setPrice('');
fetchPriceAlerts();
} catch (error) {
setError('Error setting price alert');
}
};
const fetchPriceAlerts = async () => {
try {
const alerts = await getPriceAlerts(userId);
setAlerts(alerts);
} catch (error) {
setError('Error fetching price alerts');
}
};
useEffect(() => {
fetchPriceAlerts();
}, [userId]);
return (
<View>
<TextInput
placeholder="Enter Route"
value={routeName}
onChangeText={setRouteName}
/>
<TextInput
placeholder="Enter Price"
value={price}
onChangeText={setPrice}
/>
<Button title="Set Alert" onPress={handleSetAlert} />
{error ? <Text>{error}</Text> : null}
<FlatList
data={alerts}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View>
<Text>Route: {item.route}</Text>
<Text>Price: {item.price}</Text>
</View>
)}
/>
</View>
);
};
export default PriceAlertScreen;
In-App Reviews and Ratings
Step 1: Set Up API Integration
Create a service to handle reviews and ratings-related API requests.
ReviewService.js
// src/services/ReviewService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.reviews.com'; // Replace with actual API URL
const submitReview = async (userId, airlineId, rating, comment) => {
try {
const response = await axios.post(`${API_BASE_URL}/reviews`, { userId, airlineId, rating, comment });
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
const getReviews = async (airlineId) => {
try {
const response = await axios.get(`${API_BASE_URL}/airlines/${airlineId}/reviews`);
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { submitReview, getReviews };
Step 2: Implement Reviews and Ratings Screen
ReviewScreen.js
// src/screens/ReviewScreen.js
import React, { useEffect, useState } from 'react';
import { View, TextInput, Button, Text, FlatList } from 'react-native';
import { submitReview, getReviews } from '../services/ReviewService';
const ReviewScreen = ({ route }) => {
const { userId, airlineId } = route.params;
const [rating, setRating] = useState('');
const [comment, setComment] = useState('');
const [reviews, setReviews] = useState([]);
const [error, setError] = useState('');
const handleSubmitReview = async () => {
try {
await submitReview(userId, airlineId, rating, comment);
setRating('');
setComment('');
fetchReviews();
} catch (error) {
setError('Error submitting review');
}
};
const fetchReviews = async () => {
try {
const reviews = await getReviews(airlineId);
setReviews(reviews);
} catch (error) {
setError('Error fetching reviews');
}
};
useEffect(() => {
fetchReviews();
}, [airlineId]);
return (
<View>
<TextInput
placeholder="Enter Rating"
value={rating}
onChangeText={setRating}
/>
<TextInput
placeholder="Enter Comment"
value={comment}
onChangeText={setComment}
/>
<Button title="Submit Review" onPress={handleSubmitReview} />
{error ? <Text>{error}</Text> : null}
<FlatList
data={reviews}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View>
<Text>Rating: {item.rating}</Text>
<Text>Comment: {item.comment}</Text>
<Text>Date: {new Date(item.createdAt).toLocaleString()}</Text>
</View>
)}
/>
</View>
);
};
export default ReviewScreen;
Navigation Setup
Update your App.js
to include the new screens.
App.js
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import UserProfileScreen from './src/screens/UserProfileScreen';
import PaymentMethodsScreen from './src/screens/PaymentMethodsScreen';
import BookingHistoryScreen from './src/screens/Booking
HistoryScreen';
import FlightSearchScreen from './src/screens/FlightSearchScreen';
import FlightDetailsScreen from './src/screens/FlightDetailsScreen';
import BookingScreen from './src/screens/BookingScreen';
import PaymentScreen from './src/screens/PaymentScreen';
import PaymentHistoryScreen from './src/screens/PaymentHistoryScreen';
import FlightStatusScreen from './src/screens/FlightStatusScreen';
import ChatScreen from './src/screens/ChatScreen';
import CustomerServiceScreen from './src/screens/CustomerServiceScreen';
import LoyaltyScreen from './src/screens/LoyaltyScreen';
import PriceAlertScreen from './src/screens/PriceAlertScreen';
import ReviewScreen from './src/screens/ReviewScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="FlightSearch">
<Stack.Screen name="FlightSearch" component={FlightSearchScreen} />
<Stack.Screen name="FlightDetails" component={FlightDetailsScreen} />
<Stack.Screen name="Booking" component={BookingScreen} />
<Stack.Screen name="Payment" component={PaymentScreen} />
<Stack.Screen name="PaymentHistory" component={PaymentHistoryScreen} />
<Stack.Screen name="UserProfile" component={UserProfileScreen} />
<Stack.Screen name="PaymentMethods" component={PaymentMethodsScreen} />
<Stack.Screen name="BookingHistory" component={BookingHistoryScreen} />
<Stack.Screen name="FlightStatus" component={FlightStatusScreen} />
<Stack.Screen name="Chat" component={ChatScreen} />
<Stack.Screen name="CustomerService" component={CustomerServiceScreen} />
<Stack.Screen name="Loyalty" component={LoyaltyScreen} />
<Stack.Screen name="PriceAlert" component={PriceAlertScreen} />
<Stack.Screen name="Review" component={ReviewScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
This setup provides a basic structure for integrating loyalty programs, price alerts, and in-app reviews and ratings in your React Native app.
Implementing multi-language support, currency conversion, weather forecasts, and offline access in your React Native app requires various integrations and configurations. Let's go through each feature step-by-step.
Multi-language Support
Step 1: Install and Configure i18n
-
Install
react-i18next
andi18next
:
npm install react-i18next i18next
npm install @react-native-async-storage/async-storage
-
Create
i18n.js
:
// src/i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import AsyncStorage from '@react-native-async-storage/async-storage';
import en from './locales/en.json';
import es from './locales/es.json';
const languageDetector = {
type: 'languageDetector',
async: true,
detect: async (callback) => {
const language = await AsyncStorage.getItem('user-language');
callback(language || 'en');
},
init: () => {},
cacheUserLanguage: async (language) => {
await AsyncStorage.setItem('user-language', language);
},
};
i18n
.use(languageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
resources: {
en: { translation: en },
es: { translation: es },
},
interpolation: {
escapeValue: false,
},
});
export default i18n;
-
Create translation files (
en.json
,es.json
):-
src/locales/en.json
:
{ "welcome": "Welcome", "search": "Search", "flight_status": "Flight Status", "profile": "Profile" }
-
-
src/locales/es.json
:
{ "welcome": "Bienvenido", "search": "Buscar", "flight_status": "Estado del vuelo", "profile": "Perfil" }
- Wrap your App with i18next Provider:
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { I18nextProvider } from 'react-i18next';
import i18n from './src/i18n';
import UserProfileScreen from './src/screens/UserProfileScreen';
import FlightSearchScreen from './src/screens/FlightSearchScreen';
// Other imports...
const Stack = createStackNavigator();
const App = () => {
return (
<I18nextProvider i18n={i18n}>
<NavigationContainer>
<Stack.Navigator initialRouteName="FlightSearch">
<Stack.Screen name="FlightSearch" component={FlightSearchScreen} />
<Stack.Screen name="UserProfile" component={UserProfileScreen} />
{/* Other screens */}
</Stack.Navigator>
</NavigationContainer>
</I18nextProvider>
);
};
export default App;
- Use Translations in Components:
// src/screens/FlightSearchScreen.js
import React from 'react';
import { View, Text } from 'react-native';
import { useTranslation } from 'react-i18next';
const FlightSearchScreen = () => {
const { t } = useTranslation();
return (
<View>
<Text>{t('welcome')}</Text>
<Text>{t('search')}</Text>
</View>
);
};
export default FlightSearchScreen;
Currency Converter
Step 1: Set Up API Integration
Create a service to handle currency conversion-related API requests.
CurrencyService.js
// src/services/CurrencyService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.currencyapi.com'; // Replace with actual API URL
const getExchangeRate = async (baseCurrency, targetCurrency) => {
try {
const response = await axios.get(`${API_BASE_URL}/latest`, {
params: {
base: baseCurrency,
symbols: targetCurrency,
},
});
return response.data.rates[targetCurrency];
} catch (error) {
console.error(error);
throw error;
}
};
export { getExchangeRate };
Step 2: Implement Currency Converter
CurrencyConverter.js
// src/components/CurrencyConverter.js
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Picker, Button } from 'react-native';
import { getExchangeRate } from '../services/CurrencyService';
const CurrencyConverter = () => {
const [amount, setAmount] = useState('');
const [convertedAmount, setConvertedAmount] = useState('');
const [baseCurrency, setBaseCurrency] = useState('USD');
const [targetCurrency, setTargetCurrency] = useState('EUR');
const [error, setError] = useState('');
const handleConvert = async () => {
try {
const rate = await getExchangeRate(baseCurrency, targetCurrency);
setConvertedAmount((parseFloat(amount) * rate).toFixed(2));
} catch (error) {
setError('Error fetching exchange rate');
}
};
return (
<View>
<TextInput
placeholder="Amount"
keyboardType="numeric"
value={amount}
onChangeText={setAmount}
/>
<Picker selectedValue={baseCurrency} onValueChange={setBaseCurrency}>
<Picker.Item label="USD" value="USD" />
<Picker.Item label="EUR" value="EUR" />
{/* Add more currencies */}
</Picker>
<Picker selectedValue={targetCurrency} onValueChange={setTargetCurrency}>
<Picker.Item label="EUR" value="EUR" />
<Picker.Item label="USD" value="USD" />
{/* Add more currencies */}
</Picker>
<Button title="Convert" onPress={handleConvert} />
{error ? <Text>{error}</Text> : null}
{convertedAmount ? <Text>Converted Amount: {convertedAmount}</Text> : null}
</View>
);
};
export default CurrencyConverter;
Weather Forecast
Step 1: Set Up API Integration
Create a service to handle weather-related API requests.
WeatherService.js
// src/services/WeatherService.js
import axios from 'axios';
const API_BASE_URL = 'https://api.weatherapi.com'; // Replace with actual API URL
const getWeather = async (city) => {
try {
const response = await axios.get(`${API_BASE_URL}/current.json`, {
params: {
key: 'YOUR_API_KEY',
q: city,
},
});
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
export { getWeather };
Step 2: Implement Weather Forecast Component
WeatherForecast.js
// src/components/WeatherForecast.js
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button } from 'react-native';
import { getWeather } from '../services/WeatherService';
const WeatherForecast = () => {
const [city, setCity] = useState('');
const [weather, setWeather] = useState(null);
const [error, setError] = useState('');
const handleGetWeather = async () => {
try {
const data = await getWeather(city);
setWeather(data);
} catch (error) {
setError('Error fetching weather data');
}
};
return (
<View>
<TextInput
placeholder="Enter City"
value={city}
onChangeText={setCity}
/>
<Button title="Get Weather" onPress={handleGetWeather} />
{error ? <Text>{error}</Text> : null}
{weather ? (
<View>
<Text>Temperature: {weather.current.temp_c}°C</Text>
<Text>Condition: {weather.current.condition.text}</Text>
</View>
) : null}
</View>
);
};
export default WeatherForecast;
Offline Access
Step 1: Install and Configure AsyncStorage
-
Install
@react-native-async-storage/async-storage
:
npm install @react-native-async-storage/async-storage
Step 2: Implement Offline Access for Booking Details
OfflineService.js
// src/services/OfflineService.js
import AsyncStorage from '@react-native-async-storage/async-storage';
const saveBookingDetails = async (bookingDetails) => {
try {
await AsyncStorage.setItem('bookingDetails', JSON.stringify(bookingDetails));
} catch (error) {
console.error(error);
throw error;
}
};
const getBookingDetails = async () => {
try {
const bookingDetails = await AsyncStorage.getItem('bookingDetails');
return bookingDetails ? JSON.parse(bookingDetails) : null;
} catch (error) {
console.error(error);
throw error;
}
};
export { saveBookingDetails, getBookingDetails };
Step 3: Implement Offline Booking Details Screen
OfflineBookingDetailsScreen
.js
// src/screens/OfflineBookingDetailsScreen.js
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { getBookingDetails } from '../services/OfflineService';
const OfflineBookingDetailsScreen = () => {
const [bookingDetails, setBookingDetails] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
const fetchBookingDetails = async () => {
try {
const details = await getBookingDetails();
setBookingDetails(details);
} catch (error) {
setError('Error fetching booking details');
}
};
fetchBookingDetails();
}, []);
return (
<View>
{error ? <Text>{error}</Text> : null}
{bookingDetails ? (
<View>
<Text>Flight: {bookingDetails.flight}</Text>
<Text>Date: {bookingDetails.date}</Text>
{/* Add more booking details */}
</View>
) : (
<Text>No booking details available</Text>
)}
</View>
);
};
export default OfflineBookingDetailsScreen;
Navigation Setup
Update your App.js
to include the new screens.
App.js
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import UserProfileScreen from './src/screens/UserProfileScreen';
import FlightSearchScreen from './src/screens/FlightSearchScreen';
import FlightDetailsScreen from './src/screens/FlightDetailsScreen';
import BookingScreen from './src/screens/BookingScreen';
import PaymentScreen from './src/screens/PaymentScreen';
import PaymentHistoryScreen from './src/screens/PaymentHistoryScreen';
import FlightStatusScreen from './src/screens/FlightStatusScreen';
import ChatScreen from './src/screens/ChatScreen';
import CustomerServiceScreen from './src/screens/CustomerServiceScreen';
import LoyaltyScreen from './src/screens/LoyaltyScreen';
import PriceAlertScreen from './src/screens/PriceAlertScreen';
import ReviewScreen from './src/screens/ReviewScreen';
import OfflineBookingDetailsScreen from './src/screens/OfflineBookingDetailsScreen';
import CurrencyConverter from './src/components/CurrencyConverter';
import WeatherForecast from './src/components/WeatherForecast';
import { I18nextProvider } from 'react-i18next';
import i18n from './src/i18n';
const Stack = createStackNavigator();
const App = () => {
return (
<I18nextProvider i18n={i18n}>
<NavigationContainer>
<Stack.Navigator initialRouteName="FlightSearch">
<Stack.Screen name="FlightSearch" component={FlightSearchScreen} />
<Stack.Screen name="UserProfile" component={UserProfileScreen} />
<Stack.Screen name="FlightDetails" component={FlightDetailsScreen} />
<Stack.Screen name="Booking" component={BookingScreen} />
<Stack.Screen name="Payment" component={PaymentScreen} />
<Stack.Screen name="PaymentHistory" component={PaymentHistoryScreen} />
<Stack.Screen name="FlightStatus" component={FlightStatusScreen} />
<Stack.Screen name="Chat" component={ChatScreen} />
<Stack.Screen name="CustomerService" component={CustomerServiceScreen} />
<Stack.Screen name="Loyalty" component={LoyaltyScreen} />
<Stack.Screen name="PriceAlert" component={PriceAlertScreen} />
<Stack.Screen name="Review" component={ReviewScreen} />
<Stack.Screen name="OfflineBookingDetails" component={OfflineBookingDetailsScreen} />
<Stack.Screen name="CurrencyConverter" component={CurrencyConverter} />
<Stack.Screen name="WeatherForecast" component={WeatherForecast} />
</Stack.Navigator>
</NavigationContainer>
</I18nextProvider>
);
};
export default App;
This setup includes multi-language support, a currency converter, a weather forecast component, and offline access for booking details. You can customize these components further based on your specific requirements and APIs.
If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!
Disclaimer: This content is generated by AI.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.