Recipe Finder

Set Up Your React Project

Open your terminal and create a new React app:

bashCopy codenpx create-react-app recipe-finder
cd recipe-finder

Step 2: Get Your API Key

  1. Sign up at Edamam.
  2. Create a new application to get your App ID and App Key.

Step 3: Create the Recipe Finder Component

Replace the content of src/App.js with the following code:

javascriptCopy codeimport React, { useState } from 'react';
import './App.css';

const App = () => {
  const [query, setQuery] = useState('');
  const [recipes, setRecipes] = useState([]);
  const [error, setError] = useState('');

  const APP_ID = 'YOUR_APP_ID'; // Replace with your Edamam App ID
  const APP_KEY = 'YOUR_APP_KEY'; // Replace with your Edamam App Key

  const fetchRecipes = async () => {
    if (!query) return;

    try {
      const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`);
      const data = await response.json();
      if (data.hits.length === 0) {
        setError('No recipes found.');
      } else {
        setRecipes(data.hits);
        setError('');
      }
    } catch (err) {
      setError('Failed to fetch recipes.');
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      fetchRecipes();
    }
  };

  return (
    <div className="App">
      <h1>Recipe Finder</h1>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        onKeyPress={handleKeyPress}
        placeholder="Enter ingredients..."
      />
      <button onClick={fetchRecipes}>Search</button>

      {error && <p className="error">{error}</p>}

      <div className="recipe-list">
        {recipes.map((item) => (
          <div key={item.recipe.label} className="recipe-card">
            <h2>{item.recipe.label}</h2>
            <img src={item.recipe.image} alt={item.recipe.label} />
            <p>Calories: {Math.round(item.recipe.calories)}</p>
            <a href={item.recipe.url} target="_blank" rel="noopener noreferrer">View Recipe</a>
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;

Step 4: Style Your App

Open src/App.css and add some styles:

cssCopy code.App {
  text-align: center;
  margin: 20px;
  font-family: Arial, sans-serif;
}

input {
  padding: 10px;
  margin-right: 10px;
  width: 200px;
}

button {
  padding: 10px;
}

.error {
  color: red;
}

.recipe-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.recipe-card {
  border: 1px solid #ccc;
  border-radius: 8px;
  margin: 10px;
  padding: 10px;
  width: 200px;
}

.recipe-card img {
  width: 100%;
  border-radius: 8px;
}

Step 5: Run Your Application

In the terminal, run:

bashCopy codenpm start

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *