Refactoring your NutritionScreen.js into smaller, reusable components is a great way to enhance code readability, maintainability, and scalability. Below, I'll guide you through separating the SearchBar, BarcodeButton, and TotalCaloriesCard into their own components. Additionally, I'll update the NutritionScreen to incorporate these new components.
Overview of Steps
-
Create Separate Component Files:
SearchBar.js
BarcodeButton.js
TotalCaloriesCard.js
-
Update NutritionScreen.js to Use the New Components
-
Ensure Proper Styling and Functionality
1. Creating Separate Component Files
Assuming you have a components directory in your project, create three new files within it.
a. components/SearchBar.js
// components/SearchBar.js
import React from 'react';
import { TextInput, StyleSheet } from 'react-native';
import { useTheme } from 'react-native-paper';
const SearchBar = ({ searchQuery, setSearchQuery }) => {
const theme = useTheme();
return (
<TextInput
style={[
styles.searchInput,
{
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface,
color: theme.colors.text,
},
]}
placeholder="Search food items..."
placeholderTextColor={theme.colors.placeholder}
value={searchQuery}
onChangeText={setSearchQuery}
returnKeyType="search"
accessibilityLabel="Search food items"
/>
);
};
const styles = StyleSheet.create({
searchInput: {
flex: 1,
height: 40,
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 10,
fontSize: 16,
},
});
export default SearchBar;
b. components/BarcodeButton.js
// components/BarcodeButton.js
import React from 'react';
import { TouchableOpacity, StyleSheet } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useTheme } from 'react-native-paper';
const BarcodeButton = ({ onPress }) => {
const theme = useTheme();
return (
<TouchableOpacity
style={[
styles.barcodeButton,
{ backgroundColor: theme.colors.surface },
]}
onPress={onPress}
accessibilityLabel="Scan barcode"
accessibilityRole="button"
>
<Icon name="barcode-scan" size={24} color={theme.colors.text} />
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
barcodeButton: {
marginLeft: 10,
padding: 8,
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
},
});
export default BarcodeButton;
c. components/TotalCaloriesCard.js
// components/TotalCaloriesCard.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useTheme } from 'react-native-paper';
const TotalCaloriesCard = ({ totals }) => {
const theme = useTheme();
return (
<View
style={[
styles.summaryContainer,
{ borderColor: theme.colors.border, backgroundColor: theme.colors.surface },
]}
>
<Text style={styles.summaryText}>Total Calories: {totals.calories} kcal</Text>
<Text style={styles.summaryText}>Protein: {totals.protein}g</Text>
<Text style={styles.summaryText}>Fat: {totals.fat}g</Text>
</View>
);
};
const styles = StyleSheet.create({
summaryContainer: {
padding: 15,
borderWidth: 1,
borderRadius: 8,
marginBottom: 15,
},
summaryText: {
fontSize: 16,
fontWeight: '600',
},
});
export default TotalCaloriesCard;
2. Updating NutritionScreen.js
Now, update your NutritionScreen.js to utilize the newly created components.
// screens/NutritionScreen.js
import React, { useState } from 'react';
import {
View,
StyleSheet,
FlatList,
TouchableOpacity,
Modal,
TextInput,
Alert,
SafeAreaView,
Text,
} 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';
// Example FoodItem Component (Optional)
const FoodItem = ({ item, isSelected, toggleSelect }) => {
const theme = useTheme();
return (
<TouchableOpacity
style={[
styles.itemContainer,
isSelected && styles.selectedItem,
{ borderColor: theme.colors.border, backgroundColor: theme.colors.surface },
]}
onPress={() => toggleSelect(item.id)}
accessibilityLabel={`Select ${item.name}`}
accessibilityRole="button"
>
<Icon name={item.icon} size={40} color={theme.colors.primary} />
<View style={styles.foodInfo}>
<Text style={[styles.foodName, { color: theme.colors.text }]}>{item.name}</Text>
<Text style={[styles.nutrients, { color: theme.colors.text }]}>
Calories: {item.calories} kcal
</Text>
<Text style={[styles.nutrients, { color: theme.colors.text }]}>
Protein: {item.protein}g | Carbs: {item.carbs}g | Fat: {item.fat}g
</Text>
</View>
{isSelected && (
<Icon name="check-circle" size={24} color={theme.colors.primary} />
)}
</TouchableOpacity>
);
};
const NutritionScreen = () => {
const theme = useTheme(); // Access 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}
/>
);
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, { backgroundColor: theme.colors.primary }]}
onPress={() => setModalVisible(true)}
accessibilityLabel="Add a new food item"
accessibilityRole="button"
>
<Icon name="plus" size={24} color="#fff" />
<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="#fff" />
<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,
{ backgroundColor: theme.colors.background },
]}
>
<Text style={[styles.modalTitle, { color: theme.colors.text }]}>
Add New Food
</Text>
<TextInput
style={[
styles.input,
{
borderColor: theme.colors.border,
color: theme.colors.text,
},
]}
placeholder="Food Name"
placeholderTextColor={theme.colors.placeholder}
value={newFood.name}
onChangeText={(text) => setNewFood({ ...newFood, name: text })}
/>
<TextInput
style={[
styles.input,
{
borderColor: theme.colors.border,
color: theme.colors.text,
},
]}
placeholder="Calories"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.calories}
onChangeText={(text) => setNewFood({ ...newFood, calories: text })}
/>
<TextInput
style={[
styles.input,
{
borderColor: theme.colors.border,
color: theme.colors.text,
},
]}
placeholder="Protein (g)"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.protein}
onChangeText={(text) => setNewFood({ ...newFood, protein: text })}
/>
<TextInput
style={[
styles.input,
{
borderColor: theme.colors.border,
color: theme.colors.text,
},
]}
placeholder="Carbs (g)"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.carbs}
onChangeText={(text) => setNewFood({ ...newFood, carbs: text })}
/>
<TextInput
style={[
styles.input,
{
borderColor: theme.colors.border,
color: theme.colors.text,
},
]}
placeholder="Fat (g)"
placeholderTextColor={theme.colors.placeholder}
keyboardType="numeric"
value={newFood.fat}
onChangeText={(text) => setNewFood({ ...newFood, fat: text })}
/>
{/* Icon selection can be enhanced with a picker */}
<TextInput
style={[
styles.input,
{
borderColor: theme.colors.border,
color: theme.colors.text,
},
]}
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>
);
};
// Optional: You can define FoodItem component in a separate file for better organization
const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flex: 1,
paddingHorizontal: 20,
paddingTop: 10, // Adjust as needed for alignment
paddingBottom: 20,
// backgroundColor handled by theming
},
headerContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 15,
},
summaryContainer: {
padding: 15,
borderWidth: 1,
borderRadius: 8,
marginBottom: 15,
// borderColor and backgroundColor handled dynamically
},
list: {
paddingBottom: 80, // To ensure content is not hidden behind the Add button
},
itemContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 15,
borderWidth: 1,
borderRadius: 8,
// borderColor and backgroundColor handled dynamically
},
selectedItem: {
backgroundColor: '#D1F2EB', // Light teal background for selection
},
foodInfo: {
marginLeft: 15,
flex: 1,
},
foodName: {
fontSize: 18,
fontWeight: 'bold',
// color handled dynamically
},
nutrients: {
marginTop: 5,
fontSize: 14,
// color handled dynamically
},
addButton: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
padding: 15,
borderRadius: 8,
position: 'absolute',
bottom: 20,
left: 20,
right: 20,
// backgroundColor handled dynamically
},
addButtonText: {
color: '#fff',
marginLeft: 10,
fontSize: 16,
fontWeight: '600',
},
floatingDeleteButton: {
position: 'absolute',
bottom: 90,
right: 20,
backgroundColor: '#E74C3C',
paddingVertical: 12,
paddingHorizontal: 20,
borderRadius: 25,
flexDirection: 'row',
alignItems: 'center',
elevation: 5,
},
floatingDeleteButtonText: {
color: '#fff',
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 handled dynamically
},
modalTitle: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 15,
textAlign: 'center',
},
input: {
borderWidth: 1,
borderRadius: 6,
padding: 10,
marginBottom: 10,
fontSize: 16,
// borderColor and color handled dynamically
},
modalButtons: {
flexDirection: 'row',
justifyContent: 'center',
marginTop: 10,
},
});
export default NutritionScreen;
3. Additional Recommendations
-
Creating Additional Components: For better scalability, consider creating separate components for FoodItem and AddFoodModal. This will further modularize your code.
-
Icon Picker Enhancement: Currently, the icon selection is a simple TextInput. You can enhance this by integrating an icon picker or dropdown to allow users to select from a list of available icons.
-
Persisting Data: If you plan to persist the food items, consider integrating a storage solution like AsyncStorage or a backend service.
-
Barcode Scanning Functionality: Implement the actual barcode scanning functionality using libraries like react-native-camera or react-native-barcode-scanner.
4. Directory Structure
Here's how your project structure might look after these changes:
project/
├── components/
│ ├── BarcodeButton.js
│ ├── SearchBar.js
│ └── TotalCaloriesCard.js
├── screens/
│ └── NutritionScreen.js
├── App.js
├── package.json
└── ...
5. Conclusion
By separating your NutritionScreen into smaller components, you've made your codebase cleaner and more maintainable. This modular approach allows for easier testing, reusability, and scalability as your application grows.
If you have any further questions or need additional assistance with other components, feel free to ask!