Your RecipeAI Mobile App project sounds exciting and well-thought-out! Below, I’ve outlined a comprehensive implementation guide to help you bring your vision to life. This includes setting up the project, creating essential components, integrating APIs, and ensuring a smooth user experience. I’ve also included code snippets where applicable to illustrate key parts of the implementation.
Implementation Guide for RecipeAI Mobile App
1. Project Setup
a. Install Expo CLI
Ensure you have Node.js installed. Then, install Expo CLI globally:
npm install -g expo-cli
b. Initialize the Expo Project
Create a new Expo project:
expo init RecipeAI-Mobile
Choose the blank template or any other preferred template.
c. Navigate to the Project Directory
cd RecipeAI-Mobile
2. Install Dependencies
Install the necessary dependencies as per your project description:
npm install react-navigation react-navigation-stack @react-navigation/native @react-navigation/native-stack
npm install styled-components
npm install axios
Additionally, install dependencies required for React Navigation:
expo install react-native-screens react-native-safe-area-context
3. Project Structure
Ensure your project structure matches the one you've outlined:
RecipeAI-Mobile/
│
├── assets/
│
├── components/
│ ├── IngredientInput.js
│ ├── RecipeCard.js
│ └── StepGuide.js
│
├── screens/
│ ├── HomeScreen.js
│ ├── RecipeScreen.js
│ └── RecipeDetailsScreen.js
│
├── services/
│ ├── pollinationsApi.js
│
├── App.js
├── app.json
└── package.json
4. Setting Up Navigation
Use React Navigation to manage the screens.
a. Configure Navigation in App.js
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import HomeScreen from './screens/HomeScreen';
import RecipeScreen from './screens/RecipeScreen';
import RecipeDetailsScreen from './screens/RecipeDetailsScreen';
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} options={{ title: 'RecipeAI' }} />
<Stack.Screen name="Recipes" component={RecipeScreen} />
<Stack.Screen name="RecipeDetails" component={RecipeDetailsScreen} options={{ title: 'Recipe Details' }} />
</Stack.Navigator>
</NavigationContainer>
);
}
5. Creating Reusable Components
a. IngredientInput Component
Allows users to input ingredients manually or select from presets.
// components/IngredientInput.js
import React, { useState } from 'react';
import { View, TextInput, Button, ScrollView } from 'react-native';
import styled from 'styled-components/native';
const PresetContainer = styled.View`
flex-direction: row;
flex-wrap: wrap;
margin-top: 10px;
`;
const PresetTag = styled.TouchableOpacity`
background-color: #ff6347;
padding: 8px 12px;
border-radius: 15px;
margin: 5px;
`;
const PresetText = styled.Text`
color: white;
`;
const IngredientInput = ({ addIngredient }) => {
const [ingredient, setIngredient] = useState('');
const presetIngredients = ['Tomato', 'Cheese', 'Pepper', 'Garlic', 'Onion', 'Basil'];
const handleAdd = () => {
if (ingredient.trim() !== '') {
addIngredient(ingredient.trim());
setIngredient('');
}
};
return (
<View>
<TextInput
placeholder="Enter ingredient"
value={ingredient}
onChangeText={setIngredient}
style={{
borderWidth: 1,
borderColor: '#ccc',
padding: 10,
borderRadius: 5,
}}
/>
<Button title="Add" onPress={handleAdd} />
<PresetContainer>
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
{presetIngredients.map((item) => (
<PresetTag key={item} onPress={() => addIngredient(item)}>
<PresetText>{item}</PresetText>
</PresetTag>
))}
</ScrollView>
</PresetContainer>
</View>
);
};
export default IngredientInput;
b. RecipeCard Component
Displays individual recipe suggestions with images.
// components/RecipeCard.js
import React from 'react';
import { TouchableOpacity } from 'react-native';
import styled from 'styled-components/native';
const Card = styled.View`
background-color: #fff;
border-radius: 10px;
overflow: hidden;
margin: 10px 0;
elevation: 3;
`;
const RecipeImage = styled.Image`
width: 100%;
height: 200px;
`;
const RecipeInfo = styled.View`
padding: 10px;
`;
const RecipeTitle = styled.Text`
font-size: 18px;
font-weight: bold;
`;
const RecipeCard = ({ recipe, onPress }) => {
return (
<TouchableOpacity onPress={onPress}>
<Card>
<RecipeImage source={{ uri: recipe.image }} />
<RecipeInfo>
<RecipeTitle>{recipe.title}</RecipeTitle>
</RecipeInfo>
</Card>
</TouchableOpacity>
);
};
export default RecipeCard;
c. StepGuide Component
Provides step-by-step cooking instructions.
// components/StepGuide.js
import React from 'react';
import { ScrollView, Text } from 'react-native';
import styled from 'styled-components/native';
const StepContainer = styled.View`
padding: 15px;
`;
const StepText = styled.Text`
font-size: 16px;
margin-bottom: 10px;
`;
const StepGuide = ({ steps }) => {
return (
<ScrollView>
<StepContainer>
{steps.map((step, index) => (
<StepText key={index}>
{index + 1}. {step}
</StepText>
))}
</StepContainer>
</ScrollView>
);
};
export default StepGuide;
6. Implementing API Integration
Create a service module to handle API calls to Pollinations AI.
// services/pollinationsApi.js
import axios from 'axios';
const TEXT_API_URL = 'https://text.pollinations.ai/';
const IMAGE_API_URL = 'https://pollinations.ai/p/';
export const getRecipe = async (ingredients) => {
try {
const prompt = `Generate a recipe with ${ingredients.join(', ')} for 3 people. It should be easy to cook for dinner.`;
const response = await axios.post(TEXT_API_URL, { prompt });
return response.data;
} catch (error) {
console.error('Error fetching recipe:', error);
throw error;
}
};
export const improveRecipe = async (ingredients) => {
try {
const prompt = `These are the available ingredients: ${ingredients.join(', ')}. Suggest additional ingredients to improve the recipe.`;
const response = await axios.post(TEXT_API_URL, { prompt });
return response.data;
} catch (error) {
console.error('Error improving recipe:', error);
throw error;
}
};
export const getRecipeImage = async (recipeDescription) => {
try {
const prompt = `A vibrant image of ${recipeDescription}.`;
const response = await axios.post(IMAGE_API_URL, { prompt });
return response.data;
} catch (error) {
console.error('Error fetching recipe image:', error);
throw error;
}
};
Note: Ensure that the APIs at pollinations.ai are accessible and you have the necessary permissions or API keys if required. Check their documentation for authentication if necessary.
7. Building Screens
a. HomeScreen
Handles ingredient input and fetching recipe suggestions.
// screens/HomeScreen.js
import React, { useState } from 'react';
import { View, Button, FlatList, Text, ActivityIndicator, Alert } from 'react-native';
import styled from 'styled-components/native';
import IngredientInput from '../components/IngredientInput';
import RecipeCard from '../components/RecipeCard';
import { getRecipe, improveRecipe, getRecipeImage } from '../services/pollinationsApi';
const Container = styled.View`
flex: 1;
padding: 20px;
background-color: #f5f5f5;
`;
const HomeScreen = ({ navigation }) => {
const [ingredients, setIngredients] = useState([]);
const [recipes, setRecipes] = useState([]);
const [loading, setLoading] = useState(false);
const addIngredient = (ingredient) => {
if (!ingredients.includes(ingredient)) {
setIngredients([...ingredients, ingredient]);
} else {
Alert.alert('Duplicate Ingredient', 'This ingredient is already added.');
}
};
const removeIngredient = (ingredient) => {
setIngredients(ingredients.filter((item) => item !== ingredient));
};
const fetchRecipes = async () => {
if (ingredients.length === 0) {
Alert.alert('No Ingredients', 'Please add at least one ingredient.');
return;
}
setLoading(true);
try {
const recipeData = await getRecipe(ingredients);
// Assume recipeData contains title, description, steps
// Generate images for each recipe
const recipesWithImages = await Promise.all(
recipeData.recipes.map(async (recipe) => {
const image = await getRecipeImage(recipe.title);
return { ...recipe, image: image.url || 'https://via.placeholder.com/150' }; // Fallback image
})
);
setRecipes(recipesWithImages);
} catch (error) {
Alert.alert('Error', 'Failed to fetch recipes. Please try again.');
}
setLoading(false);
};
const handleImprove = async () => {
try {
const improvement = await improveRecipe(ingredients);
Alert.alert('Improvement Suggestion', improvement.suggestion);
} catch (error) {
Alert.alert('Error', 'Failed to get improvement suggestions.');
}
};
return (
<Container>
<IngredientInput addIngredient={addIngredient} />
<View style={{ flexDirection: 'row', flexWrap: 'wrap', marginTop: 10 }}>
{ingredients.map((item) => (
<View
key={item}
style={{
backgroundColor: '#87cefa',
padding: 5,
borderRadius: 15,
margin: 5,
flexDirection: 'row',
alignItems: 'center',
}}
>
<Text style={{ color: '#fff' }}>{item}</Text>
<Button title="x" onPress={() => removeIngredient(item)} color="#fff" />
</View>
))}
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 20 }}>
<Button title="Improve" onPress={handleImprove} />
<Button title="Find Recipes" onPress={fetchRecipes} />
</View>
{loading ? (
<ActivityIndicator size="large" color="#0000ff" style={{ marginTop: 20 }} />
) : (
<FlatList
data={recipes}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<RecipeCard
recipe={item}
onPress={() => navigation.navigate('RecipeDetails', { recipe: item })}
/>
)}
style={{ marginTop: 20 }}
/>
)}
</Container>
);
};
export default HomeScreen;
b. RecipeScreen
(Optional) If you have a separate screen to list recipes before navigating to details. Since HomeScreen already lists recipes, you might skip this or integrate functionality as needed.
c. RecipeDetailsScreen
Displays detailed steps for cooking the selected recipe.
// screens/RecipeDetailsScreen.js
import React from 'react';
import { View, Text, ScrollView } from 'react-native';
import styled from 'styled-components/native';
import StepGuide from '../components/StepGuide';
const Container = styled.View`
flex: 1;
padding: 20px;
background-color: #fff;
`;
const RecipeImage = styled.Image`
width: 100%;
height: 200px;
border-radius: 10px;
`;
const Title = styled.Text`
font-size: 24px;
font-weight: bold;
margin-top: 15px;
`;
const IngredientsList = styled.View`
margin-top: 15px;
`;
const IngredientItem = styled.Text`
font-size: 16px;
`;
const RecipeDetailsScreen = ({ route }) => {
const { recipe } = route.params;
return (
<ScrollView>
<Container>
<RecipeImage source={{ uri: recipe.image }} />
<Title>{recipe.title}</Title>
<IngredientsList>
<Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 5 }}>Ingredients:</Text>
{recipe.ingredients.map((item, index) => (
<IngredientItem key={index}>• {item}</IngredientItem>
))}
</IngredientsList>
<StepGuide steps={recipe.steps} />
</Container>
</ScrollView>
);
};
export default RecipeDetailsScreen;
Note: Ensure that your recipe object has the necessary fields like title, image, ingredients, and steps.
8. Styling with Styled-Components
You’ve already started using styled-components for consistent styling. Continue to define styled components for different UI elements to maintain a clean and modular style approach.
9. Handling State Management
For this project, React’s built-in useState and useEffect hooks should suffice. However, if the app scales, consider using Context API or state management libraries like Redux.
10. Testing and Debugging
a. Run the App Locally
Use Expo to run the app on an emulator or physical device.
expo start
b. Debugging Tips
- Use React Native Debugger or the built-in debugging tools in Expo.
- Console log responses from APIs to ensure data is being fetched correctly.
- Handle edge cases, such as empty ingredient lists or API failures.
11. Enhancing User Experience
a. Loading Indicators
Show loading indicators when fetching data to inform users that a process is ongoing.
b. Error Handling
Gracefully handle errors and inform users with meaningful messages.
c. Responsive Design
Ensure the app looks good on various screen sizes and orientations.
12. Future Enhancements
You've outlined some great future features. Here’s how you can approach them:
a. Dietary Preferences
- Add filters on the HomeScreen to select dietary preferences.
- Modify your API prompts to include these preferences when generating recipes.
b. Shopping List Generator
- Allow users to add recipes to a shopping list.
- Store the missing ingredients and display them in a separate list.
c. Feedback Mechanism
- Add a rating system for recipes.
- Use feedback to refine future AI suggestions.
Additional Code Snippets
1. Handling API Responses
Assuming the getRecipe API returns data in the following format:
{
"recipes": [
{
"id": 1,
"title": "Tomato Basil Pasta",
"description": "A delicious tomato and basil pasta.",
"ingredients": ["Tomato", "Basil", "Pasta", "Salt", "Pepper"],
"steps": ["Boil pasta.", "Prepare the sauce.", "Mix and serve."]
},
// More recipes...
]
}
Ensure your getRecipe function parses this structure correctly.
2. Saving Recipes Locally (Optional)
If you decide to implement data storage for history or favorites, consider using AsyncStorage or integrating MongoDB for persistent storage.
npm install @react-native-async-storage/async-storage
// Example of saving recipes locally
import AsyncStorage from '@react-native-async-storage/async-storage';
const saveRecipe = async (recipe) => {
try {
const existingRecipes = await AsyncStorage.getItem('savedRecipes');
let recipes = existingRecipes ? JSON.parse(existingRecipes) : [];
recipes.push(recipe);
await AsyncStorage.setItem('savedRecipes', JSON.stringify(recipes));
Alert.alert('Success', 'Recipe saved successfully!');
} catch (error) {
console.error('Error saving recipe:', error);
}
};
3. Example of Fetching API Data with Error Handling
// Example usage in HomeScreen
const fetchRecipes = async () => {
if (ingredients.length === 0) {
Alert.alert('No Ingredients', 'Please add at least one ingredient.');
return;
}
setLoading(true);
try {
const recipeData = await getRecipe(ingredients);
if (recipeData && recipeData.recipes) {
const recipesWithImages = await Promise.all(
recipeData.recipes.map(async (recipe) => {
const imageResponse = await getRecipeImage(recipe.title);
return { ...recipe, image: imageResponse.url || 'https://via.placeholder.com/150' };
})
);
setRecipes(recipesWithImages);
} else {
Alert.alert('No Recipes Found', 'Try different ingredients.');
}
} catch (error) {
Alert.alert('Error', 'Failed to fetch recipes. Please try again.');
}
setLoading(false);
};
Final Thoughts
Developing a mobile app like RecipeAI involves integrating multiple technologies seamlessly. Here are some final tips to ensure a smooth development process:
- Iterative Development: Start with core features and progressively add more functionalities.
- User Feedback: Continuously gather user feedback to improve the app’s usability and features.
- Performance Optimization: Ensure the app runs smoothly on different devices by optimizing images and managing state efficiently.
- Documentation: Keep your code well-documented to make future maintenance and enhancements easier.
Good luck with your RecipeAI project! If you have any specific questions or need further assistance with any part of the implementation, feel free to ask.