Certainly! Separating your code and styles enhances readability, maintainability, and scalability, especially for larger projects. Additionally, ensuring that styles are dynamic and adapt to themes (like light and dark modes) is crucial for a seamless user experience in an Expo app.
Below, I’ll guide you through separating the NutritionScreen component and its styles into distinct files while ensuring dynamic theming using react-native-paper's theming capabilities.
1. Directory Structure
First, organize your files for better modularity. Here's a suggested directory structure:
frontend/
├── Components/
│ ├── SearchBar.js
│ ├── BarcodeButton.js
│ └── TotalCaloriesCard.js
├── screens/
│ └── Nutrition/
│ ├── NutritionScreen.js
│ └── NutritionScreen.styles.js
2. Separating the Styles
NutritionScreen.styles.js
Create a separate styles file that exports a function generating styles based on the current theme. This allows styles to be dynamic and adapt to theme changes.
// frontend/screens/Nutrition/NutritionScreen.styles.js
import { StyleSheet } from 'react-native';
const getStyles = (theme) => StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: theme.colors.background, // Dynamic based on theme
paddingTop: theme.dark ? 0 : theme?.colors?.statusBarHeight || 0, // Adjust padding based on platform or theme
},
container: {
flex: 1,
paddingHorizontal: 20,
paddingTop: 10,
paddingBottom: 20,
},
headerContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 15,
},
summaryContainer: {
padding: 15,
borderWidth: 1,
borderRadius: 8,
marginBottom: 15,
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface,
},
list: {
paddingBottom: 100, // Ensure content is visible behind floating buttons
},
itemContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 15,
borderWidth: 1,
borderRadius: 8,
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface,
},
selectedItem: {
backgroundColor: theme.colors.primaryLight, // Define primaryLight in your theme
},
longPressedItem: {
backgroundColor: theme.colors.accentLight, // Define accentLight in your theme
},
foodInfo: {
marginLeft: 15,
flex: 1,
},
foodName: {
fontSize: 18,
fontWeight: 'bold',
color: theme.colors.text,
},
nutrients: {
marginTop: 5,
fontSize: 14,
color: theme.colors.text,
},
addButton: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
padding: 15,
borderRadius: 8,
position: 'absolute',
bottom: 20,
left: 20,
right: 20,
backgroundColor: theme.colors.primary,
},
addButtonText: {
color: theme.colors.background, // Assuming background is contrasting
marginLeft: 10,
fontSize: 16,
fontWeight: '600',
},
floatingDeleteButton: {
position: 'absolute',
bottom: 90,
right: 20,
backgroundColor: theme.colors.error, // Use theme's error color
paddingVertical: 12,
paddingHorizontal: 20,
borderRadius: 25,
flexDirection: 'row',
alignItems: 'center',
elevation: 5,
},
floatingDeleteButtonText: {
color: theme.colors.background,
fontSize: 16,
fontWeight: '600',
marginLeft: 5,
},
modalOverlay: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center',
alignItems: 'center',
},
modalContainer: {
width: '90%',
padding: 20,
borderRadius: 8,
backgroundColor: theme.colors.background,
},
modalTitle: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 15,
textAlign: 'center',
color: theme.colors.text,
},
input: {
borderWidth: 1,
borderRadius: 6,
padding: 10,
marginBottom: 10,
fontSize: 16,
borderColor: theme.colors.border,
color: theme.colors.text,
},
modalButtons: {
flexDirection: 'row',
justifyContent: 'center',
marginTop: 10,
},
});
export default getStyles;
Notes:
-
Dynamic Colors: The styles utilize theme.colors to adapt to light or dark modes. Ensure your theme defines these color properties, such as primaryLight, accentLight, error, etc.
-
Responsive Padding: Adjust paddingTop based on the platform or theme to accommodate different status bar heights.
Updating Your Theme (Optional)
To make use of primaryLight, accentLight, and other custom colors, you might need to extend your theme. If you're using react-native-paper, you can customize your theme like this:
// frontend/theme.js
import { DefaultTheme, DarkTheme } from 'react-native-paper';
export const lightTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
primaryLight: '#D1F2EB', // Example color
accentLight: '#F0F8FF', // Example color
// Add other custom colors as needed
},
};
export const darkTheme = {
...DarkTheme,
colors: {
...DarkTheme.colors,
primaryLight: '#1abc9c', // Adjusted for dark theme
accentLight: '#2980b9', // Adjusted for dark theme
// Add other custom colors as needed
},
};
Make sure to provide these themes to your app using the Provider from react-native-paper.
3. Refactoring NutritionScreen.js
Now, refactor the NutritionScreen component to utilize the separated styles.
NutritionScreen.js
// frontend/screens/Nutrition/NutritionScreen.js
import React, { useState } from 'react';
import {
View,
FlatList,
TouchableOpacity,
Modal,
TextInput,
Alert,
SafeAreaView,
Text,
Platform,
StatusBar,
} from 'react-native';
import { useTheme, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import SearchBar from '../../Components/SearchBar';
import BarcodeButton from '../../Components/BarcodeButton';
import TotalCaloriesCard from '../../Components/TotalCaloriesCard';
import getStyles from './NutritionScreen.styles';
// FoodItem Component
const FoodItem = ({ item, isSelected, toggleSelect, styles }) => {
const [isLongPressed, setIsLongPressed] = useState(false);
return (
<TouchableOpacity
style={[
styles.itemContainer,
isSelected && styles.selectedItem,
isLongPressed && styles.longPressedItem,
]}
onPress={() => toggleSelect(item.id)}
onLongPress={() => setIsLongPressed(true)}
onPressOut={() => setIsLongPressed(false)}
accessibilityLabel={`Select ${item.name}`}
accessibilityRole="button"
>
<Icon name={item.icon} size={40} color={styles.iconColor} />
<View style={styles.foodInfo}>
<Text style={styles.foodName}>{item.name}</Text>
<Text style={styles.nutrients}>
Calories: {item.calories} kcal
</Text>
<Text style={styles.nutrients}>
Protein: {item.protein}g | Carbs: {item.carbs}g | Fat: {item.fat}g
</Text>
</View>
{isSelected && (
<Icon name="check-circle" size={24} color={styles.iconColor} />
)}
</TouchableOpacity>
);
};
const NutritionScreen = () => {
const theme = useTheme();
const styles = getStyles(theme); // Get styles based on the current theme
// State to manage food items
const [foodItems, setFoodItems] = useState([
{
id: '1',
name: 'Apple',
calories: 95,
protein: 0.5,
carbs: 25,
fat: 0.3,
icon: 'food-apple',
},
{
id: '2',
name: 'Banana',
calories: 105,
protein: 1.3,
carbs: 27,
fat: 0.4,
icon: 'food-croissant',
},
{
id: '3',
name: 'Grilled Chicken Breast',
calories: 165,
protein: 31,
carbs: 0,
fat: 3.6,
icon: 'food-steak',
},
// Add more initial food items as needed
]);
// State for modal visibility and new food entry
const [modalVisible, setModalVisible] = useState(false);
const [newFood, setNewFood] = useState({
name: '',
calories: '',
protein: '',
carbs: '',
fat: '',
icon: 'food',
});
// State for selected items
const [selectedIds, setSelectedIds] = useState([]);
// State for search query
const [searchQuery, setSearchQuery] = useState('');
// Calculate total nutrients based on filtered items
const filteredFoodItems = foodItems.filter((item) =>
item.name.toLowerCase().includes(searchQuery.toLowerCase())
);
const totals = filteredFoodItems.reduce(
(acc, item) => {
acc.calories += parseFloat(item.calories) || 0;
acc.protein += parseFloat(item.protein) || 0;
acc.carbs += parseFloat(item.carbs) || 0;
acc.fat += parseFloat(item.fat) || 0;
return acc;
},
{ calories: 0, protein: 0, carbs: 0, fat: 0 }
);
// Handler for barcode scan (Placeholder Function)
const handleBarcodeScan = () => {
Alert.alert('Barcode Scan', 'Barcode scanning is not implemented yet.');
};
// Handler to toggle selection of items
const toggleSelect = (id) => {
setSelectedIds((prevSelectedIds) =>
prevSelectedIds.includes(id)
? prevSelectedIds.filter((selectedId) => selectedId !== id)
: [...prevSelectedIds, id]
);
};
// Handler to delete selected items
const deleteSelectedItems = () => {
Alert.alert(
'Delete Items',
'Are you sure you want to delete the selected items?',
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: () => {
setFoodItems((prevItems) =>
prevItems.filter((item) => !selectedIds.includes(item.id))
);
setSelectedIds([]);
},
},
]
);
};
// Handler to add new food item
const addNewFoodItem = () => {
const { name, calories, protein, carbs, fat, icon } = newFood;
if (!name || !calories || !protein || !carbs || !fat) {
Alert.alert('Invalid Input', 'Please fill in all fields.');
return;
}
const newItem = {
id: (foodItems.length + 1).toString(),
name,
calories: parseFloat(calories),
protein: parseFloat(protein),
carbs: parseFloat(carbs),
fat: parseFloat(fat),
icon: icon || 'food',
};
setFoodItems((prevItems) => [...prevItems, newItem]);
setNewFood({
name: '',
calories: '',
protein: '',
carbs: '',
fat: '',
icon: 'food',
});
setModalVisible(false);
};
// Render function for FlatList items
const renderItem = ({ item }) => (
<FoodItem
item={item}
isSelected={selectedIds.includes(item.id)}
toggleSelect={toggleSelect}
styles={styles}
/>
);
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
{/* Header Section */}
<View style={styles.headerContainer}>
{/* Search Bar */}
<SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} />
{/* Barcode Button */}
<BarcodeButton onPress={handleBarcodeScan} />
</View>
{/* Total Nutrients Summary */}
<TotalCaloriesCard totals={totals} />
{/* Food Items List */}
<FlatList
data={filteredFoodItems}
keyExtractor={(item) => item.id}
renderItem={renderItem}
contentContainerStyle={styles.list}
ItemSeparatorComponent={() => <View style={{ height: 10 }} />}
/>
{/* Add Food Button */}
<TouchableOpacity
style={styles.addButton}
onPress={() => setModalVisible(true)}
accessibilityLabel="Add a new food item"
accessibilityRole="button"
>
<Icon name="plus" size={24} color={styles.addButtonText.color} />
<Text style={styles.addButtonText}> Add Food</Text>
</TouchableOpacity>
{/* Floating Delete Button for Selected Items */}
{selectedIds.length > 0 && (
<TouchableOpacity
style={styles.floatingDeleteButton}
onPress={deleteSelectedItems}
accessibilityLabel="Delete selected food items"
accessibilityRole="button"
>
<Icon name="delete" size={20} color={styles.floatingDeleteButtonText.color} />
<Text style={styles.floatingDeleteButtonText}> Delete Selected</Text>
</TouchableOpacity>
)}
{/* Add Food Modal */}
<Modal
visible={modalVisible}
animationType="slide"
transparent={true}
onRequestClose={() => setModalVisible(false)}
>
<View style={styles.modalOverlay}>
<View style={styles.modalContainer}>
<Text style={styles.modalTitle}>Add New Food</Text>
<TextInput
style={styles.input}
placeholder="Food Name"
placeholderTextColor={theme.colors.placeholder}
value={newFood.name}
onChangeText={(text) => setNewFood({ ...newFood, name: text })}
/>
<TextInput
style={styles.input}
placeholder="Calories"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.calories}
onChangeText={(text) => setNewFood({ ...newFood, calories: text })}
/>
<TextInput
style={styles.input}
placeholder="Protein (g)"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.protein}
onChangeText={(text) => setNewFood({ ...newFood, protein: text })}
/>
<TextInput
style={styles.input}
placeholder="Carbs (g)"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.carbs}
onChangeText={(text) => setNewFood({ ...newFood, carbs: text })}
/>
<TextInput
style={styles.input}
placeholder="Fat (g)"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.fat}
onChangeText={(text) => setNewFood({ ...newFood, fat: text })}
/>
<TextInput
style={styles.input}
placeholder="Icon Name (e.g., food-apple)"
placeholderTextColor={theme.colors.placeholder}
value={newFood.icon}
onChangeText={(text) => setNewFood({ ...newFood, icon: text })}
/>
<View style={styles.modalButtons}>
<Button mode="contained" onPress={addNewFoodItem}>
Add
</Button>
<Button
mode="outlined"
onPress={() => setModalVisible(false)}
style={{ marginLeft: 10 }}
>
Cancel
</Button>
</View>
</View>
</View>
</Modal>
</View>
</SafeAreaView>
);
};
export default NutritionScreen;
Key Changes and Notes:
-
Dynamic Styles Usage: The getStyles function is invoked with the current theme (const styles = getStyles(theme);), ensuring that all styles adapt based on the active theme.
-
FoodItem Component Adjustments:
-
Passed the styles object as a prop to maintain separation.
-
Utilized styles.iconColor for icon colors. To accommodate this, you can define iconColor in your NutritionScreen.styles.js based on the theme:
// Inside getStyles function in NutritionScreen.styles.js
iconColor: theme.colors.primary,
-
Accessibility Enhancements: Ensured that buttons have accessibilityLabel and accessibilityRole for better accessibility support.
-
Modal Styling: The modal adapts to theme changes, ensuring text and background colors are appropriate for both light and dark modes.
-
Floating Buttons Positioning: Adjusted the positioning to prevent overlapping or hiding content, especially when multiple floating buttons are present.
4. Additional Recommendations
a. Consistent Theme Usage
Ensure that all components (SearchBar, BarcodeButton, TotalCaloriesCard, etc.) also utilize the theme for their styles. Here's an example for the SearchBar component:
// frontend/Components/SearchBar.js
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { TextInput, useTheme } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
const SearchBar = ({ searchQuery, setSearchQuery }) => {
const theme = useTheme();
const styles = StyleSheet.create({
container: {
flex: 1,
marginRight: 10,
},
input: {
backgroundColor: theme.colors.surface,
},
});
return (
<View style={styles.container}>
<TextInput
mode="outlined"
placeholder="Search Food"
placeholderTextColor={theme.colors.placeholder}
value={searchQuery}
onChangeText={setSearchQuery}
left={<TextInput.Icon name="magnify" color={theme.colors.placeholder} />}
style={styles.input}
/>
</View>
);
};
export default SearchBar;
b. Enhance Icon Selection
For the icon field in the modal, consider integrating a picker or an icon selection library to prevent users from entering invalid icon names. Libraries like react-native-vector-icons can be integrated with a picker component to allow users to select from available icons.
c. Responsive Design
Ensure that the UI components adapt to different screen sizes and orientations. Utilize Flexbox properties effectively and consider using libraries like react-native-responsive-screen for more control.
d. Performance Optimization
For larger lists, consider implementing optimizations like initialNumToRender, maxToRenderPerBatch, and utilizing React.memo for components like FoodItem to prevent unnecessary re-renders.
5. Conclusion
By separating your styles into a dedicated file and ensuring they are dynamically generated based on the current theme, you enhance the modularity and flexibility of your Expo app. This approach not only makes your code cleaner but also ensures a consistent and adaptable user interface across different themes and devices.
Feel free to further modularize your components and styles as your project grows. If you have any more questions or need further assistance, feel free to ask!