Sure! Let's refactor your NutritionScreen by creating separate components for the Search Bar, Barcode Button, and Total Calorie Card. Here's how you can do it:
1. Create the SearchBar component
components/SearchBar.js
import React from 'react';
import { TextInput, StyleSheet } from 'react-native';
import { useTheme } from 'react-native-paper';
const SearchBar = ({ searchQuery, onSearchQueryChange }) => {
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={onSearchQueryChange}
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;
2. Create the BarcodeButton component
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;
3. Create the TotalCalorieCard component
components/TotalCalorieCard.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useTheme } from 'react-native-paper';
const TotalCalorieCard = ({ totals }) => {
const theme = useTheme();
return (
<View
style={[
styles.summaryContainer,
{
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface,
},
]}
>
<Text style={[styles.summaryText, { color: theme.colors.text }]}>
Total Calories: {totals.calories} kcal
</Text>
<Text style={[styles.summaryText, { color: theme.colors.text }]}>
Protein: {totals.protein}g
</Text>
<Text style={[styles.summaryText, { color: theme.colors.text }]}>
Fat: {totals.fat}g
</Text>
</View>
);
};
const styles = StyleSheet.create({
summaryContainer: {
padding: 15,
borderWidth: 1,
borderRadius: 8,
marginBottom: 15,
},
summaryText: {
fontSize: 16,
fontWeight: '600',
marginBottom: 5,
},
});
export default TotalCalorieCard;
4. Update NutritionScreen to use the new components
screens/NutritionScreen.js
import React, { useState } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
Modal,
TextInput,
Alert,
SafeAreaView,
} from 'react-native';
import { useTheme, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
// Import your new components
import SearchBar from '../components/SearchBar';
import BarcodeButton from '../components/BarcodeButton';
import TotalCalorieCard from '../components/TotalCalorieCard';
const NutritionScreen = () => {
const theme = useTheme();
// State variables
const [foodItems, setFoodItems] = useState([
// ... your initial food items
]);
const [modalVisible, setModalVisible] = useState(false);
const [newFood, setNewFood] = useState({
name: '',
calories: '',
protein: '',
carbs: '',
fat: '',
icon: 'food',
});
const [selectedIds, setSelectedIds] = useState([]);
const [searchQuery, setSearchQuery] = useState('');
// Functions to handle search and barcode scanning
const handleBarcodeScan = () => {
// Implement barcode scanning functionality
};
const onSearchQueryChange = (text) => {
setSearchQuery(text);
};
// Compute filtered food items
const filteredFoodItems = foodItems.filter((item) =>
item.name.toLowerCase().includes(searchQuery.toLowerCase())
);
// Compute totals
const totals = filteredFoodItems.reduce(
(acc, item) => {
acc.calories += parseFloat(item.calories);
acc.protein += parseFloat(item.protein);
acc.fat += parseFloat(item.fat);
return acc;
},
{ calories: 0, protein: 0, fat: 0 }
);
// Render function for FlatList items
const renderItem = ({ item }) => {
const isSelected = selectedIds.includes(item.id);
return (
<TouchableOpacity
style={[
styles.itemContainer,
{
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface,
},
isSelected && styles.selectedItem,
]}
onPress={() => handleItemPress(item.id)}
onLongPress={() => handleItemLongPress(item.id)}
accessibilityLabel={`Food item: ${item.name}`}
accessibilityRole="button"
>
<Icon name={item.icon} size={30} 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
</Text>
<Text style={[styles.nutrients, { color: theme.colors.text }]}>
Fat: {item.fat}g
</Text>
</View>
</TouchableOpacity>
);
};
// Event handlers
const handleItemPress = (id) => {
if (selectedIds.length > 0) {
toggleSelection(id);
}
};
const handleItemLongPress = (id) => {
toggleSelection(id);
};
const toggleSelection = (id) => {
setSelectedIds((prevSelectedIds) => {
if (prevSelectedIds.includes(id)) {
return prevSelectedIds.filter((itemId) => itemId !== id);
} else {
return [...prevSelectedIds, id];
}
});
};
const deleteSelectedItems = () => {
Alert.alert(
'Delete Items',
'Are you sure you want to delete the selected items?',
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
onPress: () => {
setFoodItems((prevItems) =>
prevItems.filter((item) => !selectedIds.includes(item.id))
);
setSelectedIds([]);
},
style: 'destructive',
},
]
);
};
const addNewFood = () => {
if (
!newFood.name ||
!newFood.calories ||
!newFood.protein ||
!newFood.carbs ||
!newFood.fat
) {
Alert.alert('Error', 'Please fill out all fields.');
return;
}
const id = (foodItems.length + 1).toString();
setFoodItems([...foodItems, { ...newFood, id }]);
setNewFood({
name: '',
calories: '',
protein: '',
carbs: '',
fat: '',
icon: 'food',
});
setModalVisible(false);
};
// Main render
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
{/* Header Section */}
<View style={styles.headerContainer}>
<SearchBar
searchQuery={searchQuery}
onSearchQueryChange={onSearchQueryChange}
/>
<BarcodeButton onPress={handleBarcodeScan} />
</View>
{/* Total Nutrients Summary */}
<TotalCalorieCard 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"
>
<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"
>
<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}>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={addNewFood}>
Add
</Button>
<Button
mode="outlined"
onPress={() => setModalVisible(false)}
style={{ marginLeft: 10 }}
>
Cancel
</Button>
</View>
</View>
</View>
</Modal>
</View>
</SafeAreaView>
);
};
// Styles remain the same
const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flex: 1,
paddingHorizontal: 20,
paddingTop: 10,
paddingBottom: 20,
},
headerContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 15,
},
list: {
paddingBottom: 20,
},
itemContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 15,
borderWidth: 1,
borderRadius: 8,
},
selectedItem: {
backgroundColor: '#D1F2EB',
},
foodInfo: {
marginLeft: 15,
flex: 1,
},
foodName: {
fontSize: 18,
fontWeight: 'bold',
},
nutrients: {
marginTop: 5,
fontSize: 14,
},
addButton: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
padding: 15,
borderRadius: 8,
position: 'absolute',
bottom: 20,
left: 20,
right: 20,
},
addButtonText: {
color: '#fff',
marginLeft: 10,
fontSize: 16,
fontWeight: '600',
},
floatingDeleteButton: {
position: 'absolute',
bottom: 90,
right: 20,
backgroundColor: '#E74C3C',
paddingVertical: 12,
paddingHorizontal: 20,
borderRadius: 25,
elevation: 5,
},
floatingDeleteButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
modalOverlay: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center',
alignItems: 'center',
},
modalContainer: {
width: '90%',
padding: 20,
borderRadius: 8,
},
modalTitle: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 15,
textAlign: 'center',
},
input: {
borderWidth: 1,
borderRadius: 6,
padding: 10,
marginBottom: 10,
fontSize: 16,
},
modalButtons: {
flexDirection: 'row',
justifyContent: 'center',
marginTop: 10,
},
});
export default NutritionScreen;
5. Update your folder structure
Ensure that your project folder structure is updated to include the new components:
/components
- SearchBar.js
- BarcodeButton.js
- TotalCalorieCard.js
/screens
- NutritionScreen.js
6. Ensure imports are correct
Double-check that the import paths in NutritionScreen.js correctly point to the new components. If your NutritionScreen.js is in the screens folder and your components are in the components folder, the import statements should be:
import SearchBar from '../components/SearchBar';
import BarcodeButton from '../components/BarcodeButton';
import TotalCalorieCard from '../components/TotalCalorieCard';
7. Test your application
After refactoring, run your application to ensure everything works as expected. Make sure:
- The search bar filters the food items.
- The barcode button responds to presses.
- The total calorie card displays the correct totals.
- Adding new food items via the modal works.
- Deleting selected items functions properly.
Notes
- State Management: Since the state is managed in
NutritionScreen, you only need to pass down the necessary props to your components.
- Theming: Each component uses
useTheme() to access theming variables, ensuring consistent styling across your app.
- Styles: Components have their own stylesheets where appropriate, keeping them modular.
Optional Improvements
- Icon Picker: For the icon selection in the modal, you can enhance the user experience by using a picker or dropdown to select available icons rather than typing the icon name.
- Accessibility: Ensure all interactive elements have appropriate accessibility labels and roles.
By refactoring your code into separate components, you improve the readability and maintainability of your codebase. Each component now has a single responsibility, making it easier to test and debug.