To separate the code and styles in your HomeScreen component while ensuring dynamic styling for a mobile Expo app, you can divide your implementation into two distinct files:
HomeScreen.js: Contains the component logic and structure.
HomeScreen.styles.js: Contains the styling logic, which dynamically adapts based on the theme.
This approach enhances readability, maintainability, and scalability of your project.
1. HomeScreen.styles.js
Create a new file named HomeScreen.styles.js in the same directory as your HomeScreen.js. This file will export a function that takes the theme as a parameter and returns a StyleSheet object. This setup allows styles to dynamically adapt based on the current theme.
// frontend/screens/Home/HomeScreen.styles.js
import { StyleSheet } from 'react-native';
const createStyles = (theme) =>
StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flexGrow: 1,
padding: 20,
paddingBottom: 40,
},
title: {
fontSize: 28,
fontWeight: 'bold',
marginBottom: 20,
textAlign: 'center',
color: theme.colors.text,
},
carouselContainer: {
height: 350, // Reduced from 400 to 350
marginBottom: 20,
alignItems: 'center',
justifyContent: 'center',
},
paginationContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginTop: 10, // Position dots below the carousel
},
paginationDot: {
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: '#C4C4C4',
marginHorizontal: 4,
},
activePaginationDot: {
backgroundColor: theme.colors.primary,
},
buttonContainer: {
flexDirection: 'row',
flexWrap: 'wrap', // Allow wrapping to the next line if necessary
justifyContent: 'space-between',
marginBottom: 20,
},
actionButton: {
width: '48%', // Fit two buttons per row
marginVertical: 5,
},
buttonContent: {
height: 50, // Consistent button height
justifyContent: 'center',
},
fullWidthButton: {
width: '100%', // Stretch across the container
borderRadius: 5,
marginTop: 10,
},
card: {
borderRadius: 10,
elevation: 3,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 5,
padding: 10,
backgroundColor: theme.colors.surface,
marginTop: 10,
marginBottom: 20, // Gap below the card
},
cardTitle: {
fontSize: 20,
fontWeight: 'bold',
},
cardText: {
fontSize: 16,
marginBottom: 5,
color: theme.colors.text,
},
progressBar: {
height: 10,
borderRadius: 5,
marginVertical: 10,
},
exerciseItem: {
marginBottom: 10,
},
friendItem: {
marginBottom: 15,
},
waterTrackerContent: {
alignItems: 'center',
},
waterText: {
fontSize: 18,
marginBottom: 10,
},
waterButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '100%',
},
waterButton: {
flex: 1,
marginHorizontal: 5,
},
calorieButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '100%',
marginTop: 10,
},
calorieButton: {
flex: 1,
marginHorizontal: 5,
},
stepsButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '100%',
marginTop: 10,
},
stepsButton: {
flex: 1,
marginHorizontal: 5,
},
addExerciseButton: {
marginTop: 10,
},
});
export default createStyles;
Explanation:
-
Dynamic Colors: By passing the theme object to the createStyles function, you can access theme-based colors such as theme.colors.text and theme.colors.surface to ensure consistent theming across your app.
-
Modular Styles: Each style is modular and named clearly, making it easier to understand and maintain.
2. HomeScreen.js
Update your HomeScreen.js to utilize the separated styles. Import the createStyles function and generate the styles using the current theme.
// frontend/screens/Home/HomeScreen.js
import React, { useContext, useState } from 'react';
import {
View,
Text,
SafeAreaView,
ScrollView,
Dimensions,
Alert,
} from 'react-native';
import { AuthContext } from '../../context/AuthContext';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useTheme, ProgressBar, Button, Card } from 'react-native-paper';
import Carousel from 'react-native-reanimated-carousel';
import CarouselCard from '../../Components/CarouselCard';
import { useNavigation } from '@react-navigation/native';
import createStyles from './HomeScreen.styles'; // Import the styles
const { width: screenWidth } = Dimensions.get('window');
const HomeScreen = () => {
const { user } = useContext(AuthContext);
const theme = useTheme();
const navigation = useNavigation();
const styles = createStyles(theme); // Generate styles based on the theme
// Example data; replace with real data sources or hooks
const [caloriesConsumed, setCaloriesConsumed] = useState(1500);
const dailyCalorieGoal = 2000;
const [steps, setSteps] = useState(7500);
const dailyStepGoal = 10000;
const [exercises, setExercises] = useState([
{ id: '1', name: 'Push Ups', duration: '30 mins' },
{ id: '2', name: 'Running', duration: '45 mins' },
]);
const [friends, setFriends] = useState([
{ id: '1', name: 'Alice', progress: 60 },
{ id: '2', name: 'Bob', progress: 80 },
]);
// State for Carousel Pagination
const [activeSlide, setActiveSlide] = useState(0);
// Water Tracker State
const [waterIntake, setWaterIntake] = useState(0); // Number of glasses consumed
const dailyWaterGoal = 8; // Daily water intake goal
// Water Tracker Handlers
const addWater = () => {
if (waterIntake < dailyWaterGoal) {
setWaterIntake(waterIntake + 1);
} else {
Alert.alert('Great Job!', 'You have reached your daily water intake goal!');
}
};
const resetWater = () => {
setWaterIntake(0);
};
// Carousel Data
const carouselItems = [
{
title: 'Calorie Tracker',
iconName: 'fire',
content: (
<View>
<Text style={styles.cardText}>
Consumed: {caloriesConsumed} kcal
</Text>
<ProgressBar
progress={caloriesConsumed / dailyCalorieGoal}
color={theme.colors.primary}
style={styles.progressBar}
/>
<Text style={styles.cardText}>
Remaining: {dailyCalorieGoal - caloriesConsumed} kcal
</Text>
<View style={styles.calorieButtons}>
<Button
mode="contained"
onPress={() => setCaloriesConsumed(caloriesConsumed + 100)}
icon="plus"
accessibilityLabel="Add 100 kcal"
accessibilityRole="button"
style={styles.calorieButton}
>
Add 100 kcal
</Button>
<Button
mode="outlined"
onPress={() => setCaloriesConsumed(0)}
icon="refresh"
accessibilityLabel="Reset calories"
accessibilityRole="button"
style={styles.calorieButton}
>
Reset
</Button>
</View>
</View>
),
buttonTitle: 'Add Food',
onPress: () => navigation.navigate('Nutrition'), // Ensure 'Nutrition' is registered
},
{
title: 'Macro Nutrients',
iconName: 'food',
content: (
<View>
<Text style={styles.cardText}>Protein: 120g</Text>
<ProgressBar
progress={120 / 200} // Example: 200g/day goal
color="#8BC34A"
style={styles.progressBar}
/>
<Text style={styles.cardText}>Carbs: 250g</Text>
<ProgressBar
progress={250 / 300} // Example: 300g/day goal
color="#03A9F4"
style={styles.progressBar}
/>
<Text style={styles.cardText}>Fat: 70g</Text>
<ProgressBar
progress={70 / 100} // Example: 100g/day goal
color="#FF9800"
style={styles.progressBar}
/>
</View>
),
buttonTitle: undefined,
onPress: undefined,
},
{
title: 'Steps Tracker',
iconName: 'walk',
content: (
<View>
<Text style={styles.cardText}>Steps Taken: {steps}</Text>
<ProgressBar
progress={steps / dailyStepGoal}
color={theme.colors.primary}
style={styles.progressBar}
/>
<View style={styles.stepsButtons}>
<Button
mode="contained"
onPress={() => setSteps(steps + 500)}
icon="plus"
accessibilityLabel="Add 500 steps"
accessibilityRole="button"
style={styles.stepsButton}
>
Add 500 Steps
</Button>
<Button
mode="outlined"
onPress={() => setSteps(0)}
icon="refresh"
accessibilityLabel="Reset steps"
accessibilityRole="button"
style={styles.stepsButton}
>
Reset
</Button>
</View>
</View>
),
buttonTitle: 'View Steps',
onPress: () => navigation.navigate('Steps'), // Ensure 'Steps' is registered
},
{
title: 'Exercise Tracker',
iconName: 'dumbbell',
content: (
<View>
{exercises.map((exercise) => (
<View key={exercise.id} style={styles.exerciseItem}>
<Text style={styles.cardText}>
{exercise.name} - {exercise.duration}
</Text>
</View>
))}
<Button
mode="outlined"
onPress={() => navigation.navigate('Exercises')} // Navigate to Exercises screen
icon="plus"
accessibilityLabel="Add Exercise"
accessibilityRole="button"
style={styles.addExerciseButton}
>
Add Exercise
</Button>
</View>
),
buttonTitle: 'Add Exercise',
onPress: () => navigation.navigate('Exercises'), // Ensure 'Exercises' is registered
},
{
title: 'Water Tracker',
iconName: 'cup-water',
content: (
<View>
<Text style={styles.cardText}>
{waterIntake} / {dailyWaterGoal} Glasses
</Text>
<ProgressBar
progress={waterIntake / dailyWaterGoal}
color="#2196F3"
style={styles.progressBar}
/>
<View style={styles.waterButtons}>
<Button
mode="contained"
onPress={addWater}
style={styles.waterButton}
icon="plus"
accessibilityLabel="Add a glass of water"
accessibilityRole="button"
>
Add Glass
</Button>
<Button
mode="outlined"
onPress={resetWater}
style={styles.waterButton}
icon="refresh"
accessibilityLabel="Reset water intake"
accessibilityRole="button"
>
Reset
</Button>
</View>
</View>
),
buttonTitle: undefined, // No single button since there are multiple actions within
onPress: undefined,
},
];
const renderCarouselItem = ({ item }) => (
<CarouselCard
title={item.title}
iconName={item.iconName}
buttonTitle={item.buttonTitle}
onPress={item.onPress}
>
{item.content}
</CarouselCard>
);
return (
<SafeAreaView style={styles.safeArea}>
<ScrollView contentContainerStyle={styles.container}>
{/* Welcome Message */}
{user ? (
<Text style={styles.title}>
Welcome, {user.name}!
</Text>
) : (
<Text style={styles.title}>
Welcome!
</Text>
)}
{/* Carousel Section */}
<View style={styles.carouselContainer}>
<Carousel
width={screenWidth * 0.9} // Width of the carousel
height={350} // Reduced height from 400 to 350
data={carouselItems}
scrollAnimationDuration={0} // Smoother transitions
onSnapToItem={(index) => setActiveSlide(index)}
renderItem={renderCarouselItem}
mode="parallax" // Carousel mode
modeConfig={{
parallaxScrollingScale: 0.9,
parallaxScrollingOffset: 50,
}}
loop={true} // Enable looping
autoPlay={false} // Disable autoplay unless needed
/>
{/* Custom Pagination */}
<View style={styles.paginationContainer}>
{carouselItems.map((_, index) => (
<View
key={index}
style={[
styles.paginationDot,
activeSlide === index && styles.activePaginationDot,
]}
/>
))}
</View>
</View>
{/* Friends Overview Card */}
<Card style={styles.card}>
<Card.Title
title="Friends"
titleStyle={styles.cardTitle}
left={(props) => (
<Icon
{...props}
name="account-group"
size={30}
color={theme.colors.primary}
/>
)}
/>
<Card.Content>
{friends.map((friend) => (
<View key={friend.id} style={styles.friendItem}>
<Text style={styles.cardText}>
{friend.name}
</Text>
<ProgressBar
progress={friend.progress / 100}
color={theme.colors.primary}
style={styles.progressBar}
/>
<Text style={styles.cardText}>
Progress: {friend.progress}%
</Text>
</View>
))}
</Card.Content>
<Card.Actions style={{ justifyContent: 'center' }}>
<Button
onPress={() => navigation.navigate('Friends')}
mode="contained"
icon="account-group"
style={styles.fullWidthButton}
contentStyle={styles.buttonContent}
accessibilityLabel="View friends progress"
accessibilityRole="button"
>
View Friends
</Button>
</Card.Actions>
</Card>
{/* Buttons Section */}
<View style={styles.buttonContainer}>
{/* Resources Button */}
<Button
mode="contained"
icon="book-open-page-variant"
onPress={() => {
console.log('Navigating to Resources');
navigation.navigate('Resources');
}}
style={styles.actionButton}
contentStyle={styles.buttonContent}
accessibilityLabel="Go to Resources"
accessibilityRole="button"
>
Resources
</Button>
{/* Calculator Button */}
<Button
mode="contained"
icon="calculator"
onPress={() => {
console.log('Navigating to Calculator');
navigation.navigate('Calculator');
}}
style={styles.actionButton}
contentStyle={styles.buttonContent}
accessibilityLabel="Open Calculator"
accessibilityRole="button"
>
Calculator
</Button>
{/* Connect Button */}
<Button
mode="contained"
icon="link"
onPress={() => {
console.log('Navigating to Connect');
navigation.navigate('Connect');
}}
style={styles.actionButton}
contentStyle={styles.buttonContent}
accessibilityLabel="Connect with Others"
accessibilityRole="button"
>
Connect
</Button>
{/* Community Button */}
<Button
mode="contained"
icon="account-supervisor"
onPress={() => {
console.log('Navigating to Community');
navigation.navigate('Community');
}}
style={styles.actionButton}
contentStyle={styles.buttonContent}
accessibilityLabel="Join Community"
accessibilityRole="button"
>
Community
</Button>
{/* Exercises Button */}
<Button
mode="contained"
icon="dumbbell"
onPress={() => {
console.log('Navigating to Exercises');
navigation.navigate('Exercises'); // Ensure 'Exercises' is registered
}}
style={styles.actionButton}
contentStyle={styles.buttonContent}
accessibilityLabel="Manage Exercises"
accessibilityRole="button"
>
Exercises
</Button>
</View>
</ScrollView>
</SafeAreaView>
);
};
export default HomeScreen;
Key Changes and Highlights:
-
Importing Styles:
- The
createStyles function from HomeScreen.styles.js is imported and invoked with the current theme object to generate the styles.
import createStyles from './HomeScreen.styles'; // Import the styles
const styles = createStyles(theme); // Generate styles based on the theme
-
Using Dynamic Styles:
-
All style props in JSX now reference the styles object, ensuring consistent theming.
-
For example:
<Text style={styles.title}>
Welcome, {user.name}!
</Text>
-
Active Pagination Dot:
-
Added an activePaginationDot style to highlight the active carousel slide.
activePaginationDot: {
backgroundColor: theme.colors.primary,
},
-
Applied conditionally in the pagination dots.
<View
key={index}
style={[
styles.paginationDot,
activeSlide === index && styles.activePaginationDot,
]}
/>
-
Clean and Organized JSX:
- The component structure remains clean, with all styling details abstracted away to the styles file.
-
Accessibility Enhancements:
- Included
accessibilityLabel and accessibilityRole props for better accessibility support.
-
Consistent Theming:
- By passing the
theme to the styles, all components adapt to theme changes (e.g., light/dark modes) seamlessly.
3. Optional: Adjusting CarouselCard for Dynamic Styles
If your CarouselCard component also requires dynamic styling based on the theme, consider applying a similar pattern. Here's a brief example:
CarouselCard.styles.js
// frontend/components/CarouselCard.styles.js
import { StyleSheet } from 'react-native';
const createCarouselCardStyles = (theme) =>
StyleSheet.create({
cardContainer: {
backgroundColor: theme.colors.surface,
borderRadius: 10,
padding: 15,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 5,
elevation: 3,
},
title: {
fontSize: 18,
fontWeight: 'bold',
color: theme.colors.text,
marginBottom: 10,
},
content: {
marginBottom: 10,
},
button: {
alignSelf: 'flex-start',
},
});
export default createCarouselCardStyles;
CarouselCard.js
// frontend/components/CarouselCard.js
import React from 'react';
import { View, Text } from 'react-native';
import { Button, useTheme } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import createCarouselCardStyles from './CarouselCard.styles';
const CarouselCard = ({ title, iconName, buttonTitle, onPress, children }) => {
const theme = useTheme();
const styles = createCarouselCardStyles(theme);
return (
<View style={styles.cardContainer}>
<Text style={styles.title}>{title}</Text>
{children}
{buttonTitle && onPress && (
<Button
mode="contained"
onPress={onPress}
icon={iconName}
style={styles.button}
accessibilityLabel={buttonTitle}
accessibilityRole="button"
>
{buttonTitle}
</Button>
)}
</View>
);
};
export default CarouselCard;
Explanation:
-
Dynamic Styles: Just like HomeScreen, CarouselCard uses a separate styles file that takes the theme as a parameter to ensure dynamic theming.
-
Conditional Rendering: The button within CarouselCard is rendered only if both buttonTitle and onPress props are provided, ensuring flexibility.
Benefits of Separating Code and Styles
-
Improved Readability: Keeping styles separate from component logic makes both easier to read and manage.
-
Reusability: Styles can be reused across different components or screens, promoting consistency.
-
Maintainability: Updates to styles or component logic can be made independently without affecting each other.
-
Scalability: As your project grows, a modular structure helps in organizing codebase efficiently.
Additional Tips
-
Consistent Naming: Ensure that style names are consistently named and descriptive to avoid confusion.
-
Theming: Utilize React Native Paper’s theming capabilities to allow for easy theme switching and customization.
-
Performance Optimization: Avoid recreating styles on every render. By placing style creation outside of the component or using memoization (e.g., useMemo), you can optimize performance. However, passing the theme as a parameter as shown above is an effective way to keep styles dynamic without significant performance overhead.
-
Documentation: Comment your styles and component logic where necessary to aid future development and onboarding.
By following this approach, you ensure that your HomeScreen is well-structured, with a clear separation between logic and presentation. This not only adheres to best practices but also makes future updates and maintenance more straightforward.