add the ExercisesScreen button // screens/HomeScreen.js import React, { useContext,…
- User
add the ExercisesScreen button // screens/HomeScreen.js
import React, { useContext, useState } from 'react'; import { View, Text, StyleSheet, SafeAreaView, ScrollView, Dimensions, } from 'react-native'; import { AuthContext } from '../context/AuthContext'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; // Ensure Icon is correctly imported 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';
const { width: screenWidth } = Dimensions.get('window');
const HomeScreen = () => { const { user } = useContext(AuthContext); const theme = useTheme(); const navigation = useNavigation();
// Example data; replace with real data sources or hooks const [caloriesConsumed] = useState(1500); const dailyCalorieGoal = 2000;
const [steps] = useState(7500); const dailyStepGoal = 10000;
const [exercises] = useState([ { id: '1', name: 'Push Ups', duration: '30 mins' }, { id: '2', name: 'Running', duration: '45 mins' }, ]);
const [friends] = useState([ { id: '1', name: 'Alice', progress: 60 }, { id: '2', name: 'Bob', progress: 80 }, ]);
// State for Carousel Pagination const [activeSlide, setActiveSlide] = useState(0);
// Updated Data for the carousel excluding Settings and Resources const carouselItems = [ { title: 'Calorie Tracker', iconName: 'fire', content: ( <Text style={[styles.cardText, { color: theme.colors.text }]}> Consumed: {caloriesConsumed} kcal <ProgressBar progress={caloriesConsumed / dailyCalorieGoal} color={theme.colors.primary} style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Remaining: {dailyCalorieGoal - caloriesConsumed} kcal ), buttonTitle: 'Add Food', onPress: () => navigation.navigate('Nutrition'), // Ensure 'Nutrition' is registered }, { title: 'Macro Nutrients', iconName: 'food', content: ( <Text style={[styles.cardText, { color: theme.colors.text }]}> Protein: 120g <ProgressBar progress={120 / 200} // Example: 200g/day goal color="#8BC34A" style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Carbs: 250g <ProgressBar progress={250 / 300} // Example: 300g/day goal color="#03A9F4" style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Fat: 70g <ProgressBar progress={70 / 100} // Example: 100g/day goal color="#FF9800" style={styles.progressBar} /> ), // Set buttonTitle and onPress to undefined instead of null buttonTitle: undefined, onPress: undefined, }, { title: 'Steps Tracker', iconName: 'walk', content: ( <Text style={[styles.cardText, { color: theme.colors.text }]}> Steps Taken: {steps} <ProgressBar progress={steps / dailyStepGoal} color={theme.colors.primary} style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Steps Remaining: {dailyStepGoal - steps} ), buttonTitle: 'View Steps', onPress: () => navigation.navigate('Steps'), // Ensure 'Steps' is registered }, { title: 'Exercise Tracker', iconName: 'dumbbell', content: ( {exercises.map((exercise) => ( <Text style={[styles.cardText, { color: theme.colors.text }]}> {exercise.name} - {exercise.duration} ))} ), buttonTitle: 'Add Exercise', onPress: () => navigation.navigate('Exercises'), // Ensure 'Exercises' is registered }, // Removed Settings and Resources from the carousel ];
const renderCarouselItem = ({ item }) => ( {item.content} );
return ( <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.colors.background }]}> {/* Welcome Message */} {user ? ( <Text style={[styles.title, { color: theme.colors.text }]}> Welcome, {user.name}! ) : ( <Text style={[styles.title, { color: theme.colors.text }]}> Welcome! )}
{/* 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={600} // Reduced duration for faster transitions onSnapToItem={(index) => setActiveSlide(index)} renderItem={renderCarouselItem} mode="parallax" // Optional: choose the carousel mode modeConfig={{ parallaxScrollingScale: 0.9, parallaxScrollingOffset: 50, }} loop={false} // Optional: enable or disable looping autoPlay={false} // Disable autoplay unless needed // Removed customAnimation to prevent TypeError /> {/* Custom Pagination */} <View style={styles.paginationContainer}> {carouselItems.map((_, index) => ( <View key={index} style={[ styles.paginationDot, activeSlide === index && { backgroundColor: theme.colors.primary }, ]} /> ))} </View> </View> {/* Buttons for Settings, Resources, Friends, and Community */} <View style={styles.buttonContainer}> <Button mode="contained" icon="cog" onPress={() => { console.log('Navigating to Settings'); navigation.navigate('Settings'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Settings </Button> <Button mode="contained" icon="book-open-page-variant" onPress={() => { console.log('Navigating to Resources'); navigation.navigate('Resources'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Resources </Button> <Button mode="contained" icon="account-group" onPress={() => { console.log('Navigating to Friends'); navigation.navigate('Friends'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Friends </Button> <Button mode="contained" icon="account-supervisor" onPress={() => { console.log('Navigating to Community'); navigation.navigate('Community'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Community </Button> </View> {/* Friends Overview Card */} <Card style={[styles.card, { backgroundColor: theme.colors.surface, marginTop: 10 }]}> <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, { color: theme.colors.text }]}> {friend.name} </Text> <ProgressBar progress={friend.progress / 100} color={theme.colors.primary} style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Progress: {friend.progress}% </Text> </View> ))} </Card.Content> <Card.Actions style={{ justifyContent: 'center' }}> <Button onPress={() => navigation.navigate('Friends')} mode="contained" // Ensures the button uses the theme's primary color icon="account-group" style={styles.fullWidthButton} // New style for consistency contentStyle={styles.buttonContent} // Ensures consistent padding > View Friends </Button> </Card.Actions> </Card> </ScrollView> </SafeAreaView>); };
const styles = StyleSheet.create({ safeArea: { flex: 1, }, container: { flexGrow: 1, padding: 20, paddingBottom: 40, }, title: { fontSize: 28, fontWeight: 'bold', marginBottom: 20, textAlign: 'center', }, carouselContainer: { height: 350, // Reduced from 400 to 350 marginBottom: 20, alignItems: 'center', justifyContent: 'center', }, paginationContainer: { flexDirection: 'row', justifyContent: 'center', marginTop: -10, // Adjusted margin to bring dots closer to carousel }, paginationDot: { width: 10, height: 10, borderRadius: 5, backgroundColor: '#C4C4C4', marginHorizontal: 4, }, buttonContainer: { flexDirection: 'row', flexWrap: 'wrap', // Allow wrapping to the next line if necessary justifyContent: 'space-between', marginBottom: 20, }, actionButton: { width: '48%', // Adjusted to fit two buttons per row marginVertical: 5, }, buttonContent: { height: 50, // Ensures consistent button height justifyContent: 'center', }, fullWidthButton: { width: '100%', // Makes the button 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, }, cardTitle: { fontSize: 20, fontWeight: 'bold', }, cardText: { fontSize: 16, marginBottom: 5, }, progressBar: { height: 10, borderRadius: 5, marginVertical: 10, }, exerciseItem: { marginBottom: 10, }, friendItem: { marginBottom: 15, }, });
export default HomeScreen;
- Assistant
To add an ExercisesScreen button to your
HomeScreen, you can integrate it alongside your existing buttons (Settings, Resources, Friends, and Community). This will provide users with a direct way to navigate to the Exercises section of your app.Below are the steps and the updated code to achieve this:
-
Choose an Appropriate Icon:
- Since you're using MaterialCommunityIcons, a suitable icon for Exercises could be
dumbbell.
- Since you're using MaterialCommunityIcons, a suitable icon for Exercises could be
-
Update the
buttonContainerto Accommodate the New Button:- Currently, your buttons are set to be
48%wide, allowing two buttons per row with some spacing. Adding a fifth button requires adjusting the layout to accommodate multiple rows or modifying the button widths. - For simplicity, we'll keep the
48%width and allow the buttons to wrap to the next line as needed.
- Currently, your buttons are set to be
-
Add the New Exercises Button:
- Insert a new
<Button>component within thebuttonContainerwith the appropriate icon and navigation.
- Insert a new
-
Ensure Navigation is Configured:
- Make sure that the
'Exercises'screen is registered in your navigation stack. If it's named differently (e.g.,'ExercisesScreen'), adjust the navigation accordingly.
- Make sure that the
-
Final Updated Code:
Here's the updated
HomeScreen.jswith the Exercises button added:// screens/HomeScreen.js import React, { useContext, useState } from 'react'; import { View, Text, StyleSheet, SafeAreaView, ScrollView, Dimensions, } from 'react-native'; import { AuthContext } from '../context/AuthContext'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; // Ensure Icon is correctly imported 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'; const { width: screenWidth } = Dimensions.get('window'); const HomeScreen = () => { const { user } = useContext(AuthContext); const theme = useTheme(); const navigation = useNavigation(); // Example data; replace with real data sources or hooks const [caloriesConsumed] = useState(1500); const dailyCalorieGoal = 2000; const [steps] = useState(7500); const dailyStepGoal = 10000; const [exercises] = useState([ { id: '1', name: 'Push Ups', duration: '30 mins' }, { id: '2', name: 'Running', duration: '45 mins' }, ]); const [friends] = useState([ { id: '1', name: 'Alice', progress: 60 }, { id: '2', name: 'Bob', progress: 80 }, ]); // State for Carousel Pagination const [activeSlide, setActiveSlide] = useState(0); // Updated Data for the carousel excluding Settings and Resources const carouselItems = [ { title: 'Calorie Tracker', iconName: 'fire', content: ( <View> <Text style={[styles.cardText, { color: theme.colors.text }]}> Consumed: {caloriesConsumed} kcal </Text> <ProgressBar progress={caloriesConsumed / dailyCalorieGoal} color={theme.colors.primary} style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Remaining: {dailyCalorieGoal - caloriesConsumed} kcal </Text> </View> ), buttonTitle: 'Add Food', onPress: () => navigation.navigate('Nutrition'), // Ensure 'Nutrition' is registered }, { title: 'Macro Nutrients', iconName: 'food', content: ( <View> <Text style={[styles.cardText, { color: theme.colors.text }]}> Protein: 120g </Text> <ProgressBar progress={120 / 200} // Example: 200g/day goal color="#8BC34A" style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Carbs: 250g </Text> <ProgressBar progress={250 / 300} // Example: 300g/day goal color="#03A9F4" style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Fat: 70g </Text> <ProgressBar progress={70 / 100} // Example: 100g/day goal color="#FF9800" style={styles.progressBar} /> </View> ), // Set buttonTitle and onPress to undefined instead of null buttonTitle: undefined, onPress: undefined, }, { title: 'Steps Tracker', iconName: 'walk', content: ( <View> <Text style={[styles.cardText, { color: theme.colors.text }]}> Steps Taken: {steps} </Text> <ProgressBar progress={steps / dailyStepGoal} color={theme.colors.primary} style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Steps Remaining: {dailyStepGoal - steps} </Text> </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, { color: theme.colors.text }]}> {exercise.name} - {exercise.duration} </Text> </View> ))} </View> ), buttonTitle: 'Add Exercise', onPress: () => navigation.navigate('Exercises'), // Ensure 'Exercises' is registered }, // Removed Settings and Resources from the carousel ]; const renderCarouselItem = ({ item }) => ( <CarouselCard title={item.title} iconName={item.iconName} buttonTitle={item.buttonTitle} onPress={item.onPress} > {item.content} </CarouselCard> ); return ( <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.colors.background }]}> <ScrollView contentContainerStyle={styles.container}> {/* Welcome Message */} {user ? ( <Text style={[styles.title, { color: theme.colors.text }]}> Welcome, {user.name}! </Text> ) : ( <Text style={[styles.title, { color: theme.colors.text }]}> 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={600} // Reduced duration for faster transitions onSnapToItem={(index) => setActiveSlide(index)} renderItem={renderCarouselItem} mode="parallax" // Optional: choose the carousel mode modeConfig={{ parallaxScrollingScale: 0.9, parallaxScrollingOffset: 50, }} loop={false} // Optional: enable or disable looping autoPlay={false} // Disable autoplay unless needed // Removed customAnimation to prevent TypeError /> {/* Custom Pagination */} <View style={styles.paginationContainer}> {carouselItems.map((_, index) => ( <View key={index} style={[ styles.paginationDot, activeSlide === index && { backgroundColor: theme.colors.primary }, ]} /> ))} </View> </View> {/* Buttons for Settings, Resources, Friends, Community, and Exercises */} <View style={styles.buttonContainer}> <Button mode="contained" icon="cog" onPress={() => { console.log('Navigating to Settings'); navigation.navigate('Settings'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Settings </Button> <Button mode="contained" icon="book-open-page-variant" onPress={() => { console.log('Navigating to Resources'); navigation.navigate('Resources'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Resources </Button> <Button mode="contained" icon="account-group" onPress={() => { console.log('Navigating to Friends'); navigation.navigate('Friends'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Friends </Button> <Button mode="contained" icon="account-supervisor" onPress={() => { console.log('Navigating to Community'); navigation.navigate('Community'); }} style={styles.actionButton} contentStyle={styles.buttonContent} // Ensures consistent padding > Community </Button> {/* New 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} // Ensures consistent padding > Exercises </Button> </View> {/* Friends Overview Card */} <Card style={[styles.card, { backgroundColor: theme.colors.surface, marginTop: 10 }]}> <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, { color: theme.colors.text }]}> {friend.name} </Text> <ProgressBar progress={friend.progress / 100} color={theme.colors.primary} style={styles.progressBar} /> <Text style={[styles.cardText, { color: theme.colors.text }]}> Progress: {friend.progress}% </Text> </View> ))} </Card.Content> <Card.Actions style={{ justifyContent: 'center' }}> <Button onPress={() => navigation.navigate('Friends')} mode="contained" // Ensures the button uses the theme's primary color icon="account-group" style={styles.fullWidthButton} // New style for consistency contentStyle={styles.buttonContent} // Ensures consistent padding > View Friends </Button> </Card.Actions> </Card> </ScrollView> </SafeAreaView> ); }; const styles = StyleSheet.create({ safeArea: { flex: 1, }, container: { flexGrow: 1, padding: 20, paddingBottom: 40, }, title: { fontSize: 28, fontWeight: 'bold', marginBottom: 20, textAlign: 'center', }, carouselContainer: { height: 350, // Reduced from 400 to 350 marginBottom: 20, alignItems: 'center', justifyContent: 'center', }, paginationContainer: { flexDirection: 'row', justifyContent: 'center', marginTop: -10, // Adjusted margin to bring dots closer to carousel }, paginationDot: { width: 10, height: 10, borderRadius: 5, backgroundColor: '#C4C4C4', marginHorizontal: 4, }, buttonContainer: { flexDirection: 'row', flexWrap: 'wrap', // Allow wrapping to the next line if necessary justifyContent: 'space-between', marginBottom: 20, }, actionButton: { width: '48%', // Adjusted to fit two buttons per row marginVertical: 5, }, buttonContent: { height: 50, // Ensures consistent button height justifyContent: 'center', }, fullWidthButton: { width: '100%', // Makes the button 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, }, cardTitle: { fontSize: 20, fontWeight: 'bold', }, cardText: { fontSize: 16, marginBottom: 5, }, progressBar: { height: 10, borderRadius: 5, marginVertical: 10, }, exerciseItem: { marginBottom: 10, }, friendItem: { marginBottom: 15, }, }); export default HomeScreen;Breakdown of Changes:
-
Added the 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} // Ensures consistent padding > Exercises </Button>- Properties Explained:
mode="contained": Provides a filled button with the primary color.icon="dumbbell": Uses the dumbbell icon from MaterialCommunityIcons.onPress: Navigates to the'Exercises'screen. Ensure that this route is correctly defined in your navigation stack.style={styles.actionButton}: Applies the existing button styles for consistency.contentStyle={styles.buttonContent}: Ensures consistent padding and height.
- Properties Explained:
-
Updated
buttonContainerfor Wrapping:- The
flexWrap: 'wrap'property inbuttonContainerallows buttons to move to the next line if there's not enough horizontal space. - With the existing
48%width for each button, adding a fifth button will automatically place it on the next available space without overlapping.
- The
-
Logging Navigation Actions:
- Each button has a
console.logstatement to help with debugging navigation actions. This can be removed or kept based on your preference.
- Each button has a
-
Ensure Navigation Registration:
- Make sure that the
'Exercises'screen is registered in your navigation stack. If using React Navigation, it might look something like this:// In your navigation configuration file import ExercisesScreen from '../screens/ExercisesScreen'; const Stack = createStackNavigator(); const AppNavigator = () => ( <Stack.Navigator> {/* Other screens */} <Stack.Screen name="Exercises" component={ExercisesScreen} /> {/* Other screens */} </Stack.Navigator> ); export default AppNavigator; - Replace
'Exercises'andExercisesScreenwith your actual route name and component if they differ.
- Make sure that the
-
Styling Considerations:
- The
buttonContainerusesflexWrap: 'wrap'andjustifyContent: 'space-between'to neatly arrange buttons in rows. - Each
actionButtonis set towidth: '48%'withmarginVertical: 5to provide spacing between buttons. - This setup allows for up to two buttons per row, with the fifth button wrapping to the next line.
- The
Final Notes:
-
Icon Availability:
- Ensure that the
dumbbellicon is available in the version ofreact-native-vector-iconsyou're using. If not, you can choose another appropriate icon from MaterialCommunityIcons.
- Ensure that the
-
Navigation Consistency:
- Consistently naming your routes helps in avoiding navigation issues. Ensure that the route name used in
navigation.navigate('Exercises')matches exactly with the one registered in your navigation stack.
- Consistently naming your routes helps in avoiding navigation issues. Ensure that the route name used in
-
Button Layout:
- If you plan to add more buttons in the future, consider using a grid layout or a more scalable button arrangement to maintain a clean UI.
-
Testing:
- After adding the button, run your app to ensure that the new Exercises button appears correctly and navigates to the intended screen without any issues.
By following these steps, you'll successfully add an ExercisesScreen button to your
HomeScreen, enhancing the navigational capabilities of your app. -