10 - "What Should I Eat?" Random Recipe Generator

Description

Create a React application that generates a random recipe when a user clicks a button.

Algorithm

  1. Initialize a state variable to store the recipe data.

  2. Define a function to fetch a random recipe from an API or a local dataset.

  3. Render a button to generate a new recipe.

  4. Render the generated recipe.

Classes

RecipeGenerator: A React component that manages the recipe state and generates a new recipe.

Code

import React, { useState, useEffect } from 'react';

function RecipeGenerator() {
  const [recipe, setRecipe] = useState(null);

  const handleGenerateRecipe = () => {
    fetch('<receipe-url>')
      .then(response => response.json())
      .then(data => setRecipe(data));
  };

  return (
    <div>
      <button onClick={handleGenerateRecipe}>What should I eat?</button>
      {recipe && (
        <div>
          <h2>{recipe.name}</h2>
          <p>Ingredients:</p>
          <ul>
            {recipe.ingredients.map(ingredient => (
              <li key={ingredient}>{ingredient}</li>
            ))}
          <p>Instructions:</p>
          <ol>
            {recipe.instructions.map(instruction => (
              <li key={instruction}>{instruction}</li>
            ))}
          </ol>
        </div>
      )}
    </div>
  );
}

export default RecipeGenerator;

Explanation

The code defines a RecipeGenerator component that utilizes the useState hook to initialize a state variable for the recipe data. The handleGenerateRecipe function fetches a random recipe from an API or a local dataset when the button is clicked. The component renders a button to generate a new recipe and the generated recipe, including its name, ingredients, and instructions.

Possible Future Enhancements

  • Implement a filter to generate recipes based on dietary restrictions.

  • Use a library like Edamam to fetch recipe data.

  • Integrate with a meal planning app to generate recipes for a week.

  • Add a feature to save favorite recipes.

Last updated