To enhance the user experience by replacing the traditional ActivityIndicator loaders with more visually appealing shimmer placeholders, you can integrate the expo-shimmer-placeholder package into your HomeScreen.tsx. This approach provides a smoother and more engaging loading experience for users.
Below are the step-by-step instructions and the updated HomeScreen.tsx code incorporating shimmer placeholders:
1. Install the expo-shimmer-placeholder Package
First, ensure that you have the expo-shimmer-placeholder package installed. You can install it using either npm or yarn:
# Using npm
npm install expo-shimmer-placeholder expo-linear-gradient
# Using yarn
yarn add expo-shimmer-placeholder expo-linear-gradient
Note: expo-linear-gradient is a dependency required by expo-shimmer-placeholder, so ensure it's installed alongside.
2. Import and Configure Shimmer Placeholder
In your HomeScreen.tsx, import the necessary modules and create a ShimmerPlaceHolder component using createShimmerPlaceholder with LinearGradient:
import { createShimmerPlaceholder } from 'expo-shimmer-placeholder';
import { LinearGradient } from 'expo-linear-gradient';
const ShimmerPlaceHolder = createShimmerPlaceholder(LinearGradient);
3. Create a Loading Placeholder Component
To maintain clean and reusable code, create a separate component that represents the loading state of a figure item. This component will display shimmer placeholders mimicking the structure of your actual content.
// LoadingFigureItem.tsx
import React from 'react';
import { View, StyleSheet } from 'react-native';
import ShimmerPlaceHolder from './ShimmerPlaceHolder'; // Adjust the path as needed
const LoadingFigureItem = ({ theme }) => {
return (
<View style={[styles.figureItem, { backgroundColor: theme.cardBackground }]}>
<ShimmerPlaceHolder
style={styles.avatar}
shimmerStyle={{ borderTopLeftRadius: 12, borderTopRightRadius: 12 }}
/>
<View style={styles.figureTextContainer}>
<ShimmerPlaceHolder style={styles.nameShimmer} />
<ShimmerPlaceHolder style={styles.categoryShimmer} />
<ShimmerPlaceHolder style={styles.descriptionShimmer} />
<ShimmerPlaceHolder style={styles.popularityShimmer} />
</View>
</View>
);
};
const styles = StyleSheet.create({
figureItem: {
borderRadius: 12,
elevation: 3,
flex: 1,
margin: 5,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
shadowColor: '#000',
},
avatar: {
height: 120,
width: '100%',
},
figureTextContainer: {
padding: 10,
},
nameShimmer: {
height: 20,
width: '60%',
marginBottom: 10,
borderRadius: 4,
},
categoryShimmer: {
height: 16,
width: '40%',
marginBottom: 10,
borderRadius: 4,
},
descriptionShimmer: {
height: 14,
width: '80%',
marginBottom: 10,
borderRadius: 4,
},
popularityShimmer: {
height: 16,
width: '30%',
borderRadius: 4,
},
});
export default LoadingFigureItem;
Explanation:
LoadingFigureItem Component: Represents a single loading figure item with shimmer placeholders for the image and text sections.
- Styles: Mimic the layout of your actual figure items to ensure consistency during the loading state.
4. Update HomeScreen.tsx to Use Shimmer Placeholders
Replace all instances of ActivityIndicator with the shimmer placeholders. Specifically:
- Remove Global
ActivityIndicator Overlay.
- Use
LoadingFigureItem Components When Data is Loading.
Here's the updated HomeScreen.tsx:
// src/screens/HomeScreen.tsx
import React, { useCallback, useContext, useState, useEffect } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
SafeAreaView,
useWindowDimensions,
RefreshControl,
ScrollView,
Alert,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure } from '../types/types';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
import { CoinContext } from '../context/CoinContext';
import uuid from 'react-native-uuid';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createShimmerPlaceholder } from 'expo-shimmer-placeholder';
import { LinearGradient } from 'expo-linear-gradient';
import LoadingFigureItem from '../components/LoadingFigureItem'; // Adjust the path as needed
const ShimmerPlaceHolder = createShimmerPlaceholder(LinearGradient);
const HomeScreen = () => {
const navigation = useNavigation();
const {
historicalFigures,
loading,
refreshing,
t,
currentTheme,
refreshFigures,
categories,
} = useApp();
const { width } = useWindowDimensions();
const { addChat } = useContext(ChatContext);
const { coins, showRewardedAd } = useContext(CoinContext);
const [selectedCategory, setSelectedCategory] = useState<string>('All');
const [isCreatingChat, setIsCreatingChat] = useState<boolean>(false);
const [isGlobalLoading, setIsGlobalLoading] = useState<boolean>(false);
const numColumns = 2;
useEffect(() => {
if (loading || isCreatingChat) {
setIsGlobalLoading(true);
} else {
setIsGlobalLoading(false);
}
}, [loading, isCreatingChat]);
const startChat = useCallback(async (figure: HistoricalFigure) => {
if (isCreatingChat) return;
setIsCreatingChat(true);
try {
const chatId = uuid.v4().toString();
console.log('Generated chatId:', chatId);
await addChat({
id: chatId,
figure,
createdAt: Date.now(),
});
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert(t('error'), t('errorStartingChat'));
} finally {
setIsCreatingChat(false);
}
}, [addChat, navigation, t, isCreatingChat]);
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
onPress={() => startChat(item)}
disabled={isCreatingChat}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
<View style={styles.figureTextContainer}>
<CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
{item.name}
</CustomText>
<CustomText style={[styles.figureCategory, { color: currentTheme.accentColor }]}>
{item.category}
</CustomText>
<CustomText
style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]}
numberOfLines={3}
>
{item.description}
</CustomText>
<CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
{t('popularity')} {item.popularity || 0}
</CustomText>
</View>
</TouchableOpacity>
), [currentTheme, startChat, t, isCreatingChat]);
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
const onRefresh = useCallback(async () => {
await refreshFigures();
}, [refreshFigures]);
const filteredFigures = selectedCategory === 'All'
? historicalFigures
: historicalFigures.filter(fig => fig.category === selectedCategory);
const renderCategoryItem = useCallback((category: string, index: number) => {
const isSelected = category === selectedCategory;
return (
<TouchableOpacity
key={`${category}-${index}`}
style={[
styles.categoryButton,
{
backgroundColor: isSelected ? currentTheme.accentColor : 'transparent',
borderColor: isSelected ? currentTheme.accentColor : currentTheme.secondaryTextColor,
}
]}
onPress={() => setSelectedCategory(category)}
>
<CustomText
style={[
styles.categoryText,
{
color: isSelected ? currentTheme.backgroundColor : currentTheme.textColor,
}
]}
>
{t(category)}
</CustomText>
</TouchableOpacity>
);
}, [selectedCategory, currentTheme, t]);
const renderCategoryRows = () => {
const halfLength = Math.ceil(categories.length / 2);
return (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.categoryRowsContainer}
>
<View>
<View style={styles.categoryRow}>
{categories.slice(0, halfLength).map((category, index) => renderCategoryItem(category, index))}
</View>
<View style={styles.categoryRow}>
{categories.slice(halfLength).map((category, index) => renderCategoryItem(category, index + halfLength))}
</View>
</View>
</ScrollView>
);
};
const renderContent = () => {
if (loading) {
// Display shimmer placeholders equivalent to figure items
return (
<FlatList
data={[...Array(4)]} // Number of placeholder items
renderItem={() => <LoadingFigureItem theme={currentTheme} />}
keyExtractor={(_, index) => `loading-${index}`}
numColumns={numColumns}
contentContainerStyle={styles.figureList}
/>
);
}
if (filteredFigures.length === 0) {
return (
<View style={styles.emptyContainer}>
<CustomText style={[styles.emptyText, { color: currentTheme.textColor }]}>
{t('noFiguresInThisCategory')}
</CustomText>
</View>
);
}
return (
<FlatList
data={filteredFigures}
renderItem={renderFigureItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.figureList}
numColumns={numColumns}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={[currentTheme.accentColor]}
tintColor={currentTheme.accentColor}
/>
}
/>
);
};
return (
<SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
<StatusBar style={currentTheme.statusBarStyle} />
<View style={styles.container}>
{/* Header */}
<View style={styles.header}>
<CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
{t('historicalFigures')}
</CustomText>
<View style={styles.headerRight}>
{/* Coin Display */}
<TouchableOpacity style={styles.coinContainer} onPress={showRewardedAd}>
<Ionicons name="flash" size={20} color={currentTheme.accentColor} />
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>
{coins}
</CustomText>
</TouchableOpacity>
{/* Settings Button */}
<TouchableOpacity
style={styles.settingsButton}
onPress={() => navigation.navigate('Settings')}
>
<Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
</TouchableOpacity>
</View>
</View>
{/* Category Selector (Two Rows, Scrollable Horizontally) */}
{renderCategoryRows()}
{/* Content */}
{renderContent()}
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flex: 1,
paddingHorizontal: 10,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 15,
paddingHorizontal: 15,
},
title: {
fontFamily: 'Poppins_700Bold',
fontSize: 24,
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
},
coinContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 5,
},
coinText: {
fontFamily: 'Poppins_700Bold',
fontSize: 18,
marginLeft: 5,
},
settingsButton: {
padding: 2,
marginLeft: 15,
},
categoryRowsContainer: {
paddingHorizontal: 5,
paddingBottom: 20,
},
categoryRow: {
flexDirection: 'row',
marginBottom: 6,
},
categoryButton: {
paddingVertical: 8,
paddingHorizontal: 10,
borderRadius: 16,
borderWidth: 1,
marginRight: 5,
},
categoryText: {
fontFamily: 'Poppins_600SemiBold',
fontSize: 14,
},
figureList: {
paddingVertical: 10,
},
figureItem: {
borderRadius: 12,
elevation: 3,
flex: 1,
margin: 5,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
shadowColor: '#000',
},
avatar: {
borderTopLeftRadius: 12,
borderTopRightRadius: 12,
height: 120,
width: '100%',
resizeMode: 'cover',
},
figureTextContainer: {
padding: 10,
},
figureName: {
fontFamily: 'Poppins_700Bold',
fontSize: 16,
textAlign: 'center',
marginBottom: 4,
},
figureCategory: {
fontFamily: 'Poppins_600SemiBold',
textAlign: 'center',
fontSize: 12,
marginBottom: 4,
},
figureDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 14,
textAlign: 'center',
marginBottom: 4,
},
popularity: {
textAlign: 'center',
fontSize: 14,
fontFamily: 'Poppins_600SemiBold',
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
emptyText: {
fontSize: 16,
textAlign: 'center',
},
});
export default HomeScreen;
5. Explanation of Changes
-
Removed ActivityIndicator:
- All instances of
ActivityIndicator have been removed to eliminate traditional loading spinners.
-
Integrated Shimmer Placeholders:
- Loading State: When
loading is true, the FlatList renders multiple LoadingFigureItem components, each displaying shimmer placeholders that mimic the structure of the actual content.
- Content State: Once the data is loaded (
loading is false), the actual content (historicalFigures) is displayed as before.
-
Simplified Global Loading State:
- The global loading overlay (
isGlobalLoading) with ActivityIndicator has been removed. Instead, the shimmer placeholders integrated within the content handle the loading indication, providing a seamless user experience.
-
LoadingFigureItem Component:
- This component creates a skeleton of the figure item using shimmer placeholders for the image and text sections, ensuring users are visually informed that content is loading.
-
Enhanced User Experience:
- Shimmer placeholders offer a more modern and appealing loading experience compared to traditional spinners, keeping users engaged while content loads.
6. Additional Recommendations
-
Customize Shimmer Styles:
- You can further customize the shimmer effects by adjusting properties like
shimmerColors, duration, and isReversed within the ShimmerPlaceHolder configuration to match your app's theme and desired aesthetics.
-
Optimize Placeholder Count:
- Adjust the number of
LoadingFigureItem components based on typical loading times and screen size to balance performance and user experience.
-
Accessibility Considerations:
- Ensure that shimmer effects do not hinder accessibility. Provide alternative indicators or ensure that screen readers can properly inform users about loading states.
By following the above steps, your HomeScreen.tsx will now utilize visually appealing shimmer placeholders instead of traditional loading indicators, enhancing the overall user experience of your application.