使用 React 构建食谱查找器网站

使用 react 构建食谱查找器网站

介绍

在本博客中,我们将使用 react 构建一个食谱查找网站。该应用程序允许用户搜索他们最喜欢的食谱,查看趋势或新食谱,并保存他们最喜欢的食谱。我们将利用 edamam api 获取实时食谱数据并将其动态显示在网站上。

项目概况

食谱查找器允许用户:

按名称搜索食谱。查看趋势和新添加的食谱。查看各个食谱的详细信息。将食谱添加到收藏夹列表并使用 localstorage 保存数据。

特征

搜索功能:用户可以通过输入查询来搜索食谱。热门食谱:显示来自 api 的当前热门食谱。新菜谱:显示来自 api 的最新菜谱。食谱详细信息:显示有关所选食谱的详细信息。收藏夹:允许用户将食谱添加到收藏夹列表,该列表保存在本地。

使用的技术

react:用于构建用户界面。react router:用于不同页面之间的导航。edamam api:用于获取食谱。css:用于设计应用程序的样式。

项目结构

src/│├── components/│   └── navbar.js│├── pages/│   ├── home.js│   ├── about.js│   ├── trending.js│   ├── newrecipe.js│   ├── recipedetail.js│   ├── contact.js│   └── favorites.js│├── app.js├── index.js├── app.css└── index.css

安装

要在本地运行此项目,请按照以下步骤操作:

克隆存储库:

   git clone https://github.com/abhishekgurjar-in/recipe-finder.git   cd recipe-finder

安装依赖项:

   npm install

启动 react 应用程序:

   npm start

从 edamam 网站获取您的 edamam api 凭证(api id 和 api 密钥)。

在进行 api 调用的页面中添加您的 api 凭据,例如 home.js、trending.js、newrecipe.js 和 recipedetail.js。

用法

应用程序.js
import react from "react";import navbar from "./components/navbar";import { route, routes } from "react-router-dom";import "./app.css";import home from "./pages/home";import about from "./pages/about";import trending from "./pages/trending";import newrecipe from "./pages/newrecipe";import recipedetail from "./pages/recipedetail";import contact from "./pages/contact";import favorites from "./pages/favorites";const app = () => {  return (                        <route path="/" element={} />        <route path="/trending" element={} />        <route path="/new-recipe" element={} />        <route path="/new-recipe" element={} />        <route path="/recipe/:id" element={} />        <route path="/about" element={} />        <route path="/contact" element={} />        <route path="/favorites" element={} />         

made with ❤️ by abhishek gurjar

主页.js

这是用户可以使用 edamam api 搜索食谱的主页。

import react, { usestate, useref, useeffect } from "react";import { iosearch } from "react-icons/io5";import { link } from "react-router-dom";const home = () => {  const [query, setquery] = usestate("");  const [recipe, setrecipe] = usestate([]);  const recipesectionref = useref(null);  const api_id = "2cbb7807";  const api_key = "17222f5be3577d4980d6ee3bb57e9f00";  const getrecipe = async () => {    if (!query) return; // add a check to ensure the query is not empty    const response = await fetch(      `https://api.edamam.com/search?q=${query}&app_id=${api_id}&app_key=${api_key}`    );    const data = await response.json();    setrecipe(data.hits);    console.log(data.hits);  };  // use useeffect to detect changes in the recipe state and scroll to the recipe section  useeffect(() => {    if (recipe.length > 0 && recipesectionref.current) {      recipesectionref.current.scrollintoview({ behavior: "smooth" });    }  }, [recipe]);  // handle key down event to trigger getrecipe on enter key press  const handlekeydown = (e) => {    if (e.key === "enter") {      getrecipe();    }  };  return (    

find your favourite recipe

setquery(e.target.value)} onkeydown={handlekeydown} // add the onkeydown event handler />
{recipe.map((item, index) => (
@@##@@

{item.recipe.label}

))}
);};export default home;
trending.js

此页面获取并显示趋势食谱。

import react, { usestate, useeffect } from "react";import { link } from "react-router-dom";const trending = () => {  const [trendingrecipes, settrendingrecipes] = usestate([]);  const [loading, setloading] = usestate(true);  const [error, seterror] = usestate(null);  const api_id = "2cbb7807";  const api_key = "17222f5be3577d4980d6ee3bb57e9f00";  useeffect(() => {    const fetchtrendingrecipes = async () => {      try {        const response = await fetch(          `https://api.edamam.com/api/recipes/v2?type=public&q=trending&app_id=${api_id}&app_key=${api_key}`        );        if (!response.ok) {          throw new error("network response was not ok");        }        const data = await response.json();        settrendingrecipes(data.hits);        setloading(false);      } catch (error) {        seterror("failed to fetch trending recipes");        setloading(false);      }    };    fetchtrendingrecipes();  }, []);  if (loading)    return (      
); if (error) return
{error}
; return (

trending recipes

{trendingrecipes.map((item, index) => (
@@##@@

{item.recipe.label}

))}
);};export default trending;
新菜谱.js

此页面获取新食谱并显示新食谱。

import react, { usestate, useeffect } from "react";import { link } from "react-router-dom";const newrecipe = () => {  const [newrecipes, setnewrecipes] = usestate([]);  const [loading, setloading] = usestate(true);  const [error, seterror] = usestate(null);  const api_id = "2cbb7807";  const api_key = "17222f5be3577d4980d6ee3bb57e9f00";  useeffect(() => {    const fetchnewrecipes = async () => {      try {        const response = await fetch(          `https://api.edamam.com/api/recipes/v2?type=public&q=new&app_id=${api_id}&app_key=${api_key}`        );        if (!response.ok) {          throw new error("network response was not ok");        }        const data = await response.json();        setnewrecipes(data.hits);        setloading(false);      } catch (error) {        seterror("failed to fetch new recipes");        setloading(false);      }    };    fetchnewrecipes();  }, []);  if (loading)    return (      
); if (error) return
{error}
; return (

new recipes

{newrecipes.map((item, index) => (
@@##@@

{item.recipe.label}

))}
);};export default newrecipe;
主页.js

此页面获取并显示主页和搜索的食谱。

import react, { usestate, useref, useeffect } from "react";import { iosearch } from "react-icons/io5";import { link } from "react-router-dom";const home = () => {  const [query, setquery] = usestate("");  const [recipe, setrecipe] = usestate([]);  const recipesectionref = useref(null);  const api_id = "2cbb7807";  const api_key = "17222f5be3577d4980d6ee3bb57e9f00";  const getrecipe = async () => {    if (!query) return; // add a check to ensure the query is not empty    const response = await fetch(      `https://api.edamam.com/search?q=${query}&app_id=${api_id}&app_key=${api_key}`    );    const data = await response.json();    setrecipe(data.hits);    console.log(data.hits);  };  // use useeffect to detect changes in the recipe state and scroll to the recipe section  useeffect(() => {    if (recipe.length > 0 && recipesectionref.current) {      recipesectionref.current.scrollintoview({ behavior: "smooth" });    }  }, [recipe]);  // handle key down event to trigger getrecipe on enter key press  const handlekeydown = (e) => {    if (e.key === "enter") {      getrecipe();    }  };  return (    

find your favourite recipe

setquery(e.target.value)} onkeydown={handlekeydown} // add the onkeydown event handler />
{recipe.map((item, index) => (
@@##@@

{item.recipe.label}

))}
);};export default home;
收藏夹.js

此页面显示最喜欢的食谱。

import react, { usestate, useeffect } from "react";import { link } from "react-router-dom";const favorites = () => {  const [favorites, setfavorites] = usestate([]);  useeffect(() => {    const savedfavorites = json.parse(localstorage.getitem("favorites")) || [];    setfavorites(savedfavorites);  }, []);  if (favorites.length === 0) {    return 
no favorite recipes found.
; } return (

favorite recipes

    {favorites.map((recipe) => (
    @@##@@

    {recipe.label}

    ))}
);};export default favorites;
recipedetail.js

此页面显示食谱。

import react, { usestate, useeffect } from "react";import { useparams } from "react-router-dom";const recipedetail = () => {  const { id } = useparams(); // use react router to get the recipe id from the url  const [recipe, setrecipe] = usestate(null);  const [loading, setloading] = usestate(true);  const [error, seterror] = usestate(null);  const [favorites, setfavorites] = usestate([]);  const api_id = "2cbb7807";  const api_key = "17222f5be3577d4980d6ee3bb57e9f00";  useeffect(() => {    const fetchrecipedetail = async () => {      try {        const response = await fetch(          `https://api.edamam.com/api/recipes/v2/${id}?type=public&app_id=${api_id}&app_key=${api_key}`        );        if (!response.ok) {          throw new error("network response was not ok");        }        const data = await response.json();        setrecipe(data.recipe);        setloading(false);      } catch (error) {        seterror("failed to fetch recipe details");        setloading(false);      }    };    fetchrecipedetail();  }, [id]);  useeffect(() => {    const savedfavorites = json.parse(localstorage.getitem("favorites")) || [];    setfavorites(savedfavorites);  }, []);  const addtofavorites = () => {    const updatedfavorites = [...favorites, recipe];    setfavorites(updatedfavorites);    localstorage.setitem("favorites", json.stringify(updatedfavorites));  };  const removefromfavorites = () => {    const updatedfavorites = favorites.filter(      (fav) => fav.uri !== recipe.uri    );    setfavorites(updatedfavorites);    localstorage.setitem("favorites", json.stringify(updatedfavorites));  };  const isfavorite = favorites.some((fav) => fav.uri === recipe?.uri);  if (loading)    return (      
); if (error) return
{error}
; return (
{recipe && (

{recipe.label}

ingredients:

    {recipe.ingredientlines.map((ingredient, index) => (
  • {ingredient}
  • ))}

instructions:

{/* note: edamam api doesn't provide instructions directly. you might need to link to the original recipe url */}

for detailed instructions, please visit the{" "} recipe instruction

{isfavorite ? ( ) : ( )}
@@##@@
);};export default recipedetail;
联系方式.js

此页面显示联系页面。

import react, { usestate } from 'react';const contact = () => {  const [name, setname] = usestate('');  const [email, setemail] = usestate('');  const [message, setmessage] = usestate('');  const [showpopup, setshowpopup] = usestate(false);  const handlesubmit = (e) => {    e.preventdefault();    // prepare the contact details object    const contactdetails = { name, email, message };    // save contact details to local storage    const savedcontacts = json.parse(localstorage.getitem('contacts')) || [];    savedcontacts.push(contactdetails);    localstorage.setitem('contacts', json.stringify(savedcontacts));    // log the form data    console.log('form submitted:', contactdetails);    // clear form fields    setname('');    setemail('');    setmessage('');    // show popup    setshowpopup(true);  };  const closepopup = () => {    setshowpopup(false);  };  return (    

contact us

setname(e.target.value)} required />
setemail(e.target.value)} required />
{showpopup && (

thank you!

your message has been submitted successfully.

)}
);};export default contact;
关于.js

此页面显示关于页面。

import React from 'react';const About = () => {  return (    

About Us

Welcome to Recipe Finder, your go-to place for discovering delicious recipes from around the world!

Our platform allows you to search for recipes based on your ingredients or dietary preferences. Whether you're looking for a quick meal, a healthy option, or a dish to impress your friends, we have something for everyone.

We use the Edamam API to provide you with a vast database of recipes. You can easily find new recipes, view detailed instructions, and explore new culinary ideas.

Features:

  • Search for recipes by ingredient, cuisine, or dietary restriction.
  • Browse new and trending recipes.
  • View detailed recipe instructions and ingredient lists.
  • Save your favorite recipes for quick access.

Our mission is to make cooking enjoyable and accessible. We believe that everyone should have the tools to cook great meals at home.

);};export default About;

现场演示

您可以在这里查看该项目的现场演示。

结论

食谱查找网站对于任何想要发现新的和流行食谱的人来说是一个强大的工具。通过利用 react 作为前端和 edamam api 来处理数据,我们可以提供无缝的用户体验。您可以通过添加分页、用户身份验证甚至更详细的过滤选项等功能来进一步自定义此项目。

随意尝试该项目并使其成为您自己的!

制作人员

api:毛豆图标:react 图标

作者

abhishek gurjar 是一位专注的 web 开发人员,热衷于创建实用且功能性的 web 应用程序。在 github 上查看他的更多项目。

{item.recipe.label}{item.recipe.label}{item.recipe.label}{item.recipe.label}{recipe.label}{recipe.label}

以上就是使用 React 构建食谱查找器网站的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1629873.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
使用 React 构建国家/地区查找应用程序
上一篇 2025年12月24日 12:49:26
使用 React 构建电影查找网站
下一篇 2025年12月24日 12:49:31

相关推荐

  • 修复Django电商项目中AJAX过滤产品列表图片不显示问题

    在Django电商项目中,当使用AJAX动态加载过滤后的产品列表时,常遇到图片无法正常显示的问题。这通常是由于前端模板中图片加载方式(如data-setbg属性结合JavaScript库)与AJAX动态内容更新机制不兼容所致。解决方案是直接在AJAX返回的HTML中使用标准的标签来渲染图片,确保浏览…

    2026年5月10日
    000
  • 开源免费PHP工具 PHP开发效率提升利器

    推荐开源免费PHP开发工具以提升效率:VS Code、Sublime Text轻量高效,PhpStorm专业强大;调试用Xdebug、Kint、Ray;依赖管理选Composer;代码质量工具包括PHPStan、Psalm、PHP_CodeSniffer;数据库管理可用%ignore_a_1%MyA…

    2026年5月10日
    000
  • css max-height属性怎么用

    max-height 属性设置元素的最大高度。 说明 该属性值会对元素的高度设置一个最高限制。因此,元素可以比指定值矮,但不能比其高。不允许指定负值。 注意:max-height 属性不包括外边距、边框和内边距。 立即学习“前端免费学习笔记(深入)”; 值描述none 默认。定义对元素被允许的最大高…

    2026年5月10日
    000
  • 修复点击时按钮抖动:CSS垂直对齐实践

    本文探讨了在Web开发中,交互式按钮(如播放/暂停按钮)在点击时发生意外垂直位移的问题。通过分析CSS样式变化对元素布局的影响,我们发现这是由于按钮不同状态下的边框样式和内边距改变,以及默认的垂直对齐行为共同作用所致。核心解决方案是利用CSS的vertical-align属性,将其设置为middle…

    2026年5月10日
    000
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    000
  • 前端缓存策略与JavaScript存储管理

    根据数据特性选择合适的存储方式并制定清晰的读写与清理逻辑,能显著提升前端性能;合理运用Cookie、localStorage、sessionStorage、IndexedDB及Cache API,结合缓存策略与定期清理机制,可在保证用户体验的同时避免安全与性能隐患。 前端缓存和JavaScript存…

    2026年5月10日
    100
  • JavaScript 动态菜单点击高亮效果实现教程

    本教程详细介绍了如何使用 JavaScript 实现动态菜单的点击高亮功能。通过事件委托和状态管理,当用户点击菜单项时,被点击项会高亮显示(绿色),同时其他菜单项恢复默认样式(白色)。这种方法避免了不必要的DOM操作,提高了性能和代码可维护性,确保了无论点击方向如何,功能都能稳定运行。 动态菜单高亮…

    2026年5月10日
    200
  • html5怎么画实线_HTML5用CSS border-style:solid画元素实线边框【绘制】

    可通过CSS的border-style属性设为solid添加实线边框:一、内联样式用border:2px solid #000;二、内部样式表统一设置如div{border:1px solid #333};三、外部CSS文件定义.my-box{border:3px solid red}并引入;四、单…

    2026年5月10日
    000
  • 谷歌浏览器如何截图 谷歌浏览器页面截图技巧

    谷歌浏览器如何截图 谷歌浏览器页面截图技巧谷歌浏览器如何截图 谷歌浏览器页面截图技巧谷歌浏览器如何截图 谷歌浏览器页面截图技巧谷歌浏览器如何截图 谷歌浏览器页面截图技巧

    使用谷歌浏览器的开发者工具截图步骤:1. 按ctrl+shift+i(windows/linux)或cmd+option+i(mac)打开开发者工具。2. 点击右上角三个点,选择”更多工具”,再选择”截图”。3. 选择截取整个页面。推荐的谷歌浏览器扩展…

    2026年5月10日 用户投稿
    100
  • css如何禁止滚动条

    css禁止滚动条的方法:1、完全隐藏,代码为【】;2、在不需要时隐藏,代码为【】;3、样式表方法。 本教程操作环境:windows7系统、css3版,DELL G3电脑。 1、完全隐藏 在里加入scroll=”no”,可隐藏滚动条;   立即学习“前端免费学习笔记(深入)”;…

    2026年5月10日
    000
  • 动态更新圆形进度条:JavaScript成绩计算器集成指南

    本文档旨在指导开发者如何将JavaScript成绩计算系统与动态圆形进度条集成,实现可视化展示平均成绩。我们将详细讲解如何修改现有的JavaScript代码,使其在计算出平均分后,能够动态更新圆形进度条的进度,从而提供更直观的用户体验。本文档包含详细的代码示例和注意事项,帮助开发者轻松实现这一功能。…

    2026年5月10日
    000
  • 如何讲html和css_讲解HTML与CSS结合使用基础【基础】

    需将HTML与CSS结合使用以实现网页结构与样式的分离:HTML定义标题、段落等语义结构,CSS控制颜色、字体等外观;可通过内联样式、内部样式表或外部CSS文件引入样式,并利用类选择器和ID选择器精准应用。 如果您希望网页不仅展示内容,还能具备基本的样式和结构布局,则需要将HTML与CSS结合使用。…

    2026年5月10日
    000
  • React组件中动态属性值的管理与同步:利用状态实现受控组件

    本教程旨在解决react组件中动态属性值同步使用的问题。我们将探讨如何利用react的`usestate` hook来管理组件内部状态,从而实现一个属性的值动态地影响另一个属性,并构建出可预测、易于维护的受控组件。文章将通过具体代码示例,详细阐述从初始化状态到处理状态更新的完整过程,并强调受控组件在…

    2026年5月10日
    000
  • CSS伪元素与固定背景:移动友好的实现策略

    本文深入探讨了如何利用CSS的::before伪元素、position: fixed和z-index属性,创建一种在移动设备上表现更稳定的全屏固定背景效果,以替代传统background-attachment: fixed可能存在的兼容性问题。教程将详细解析这些核心CSS概念及其在构建响应式布局中的…

    2026年5月10日
    000
  • PHP多维数组到复杂XML结构的SOAP序列化实践

    本文旨在解决php多维数组向复杂soap xml结构序列化时遇到的“无法序列化结果”问题。通过深入理解soap xml的结构要求,包括命名空间和类型属性,文章将指导您如何构建符合特定xml schema的php关联数组。我们将利用`spatie/array-to-xml`库,详细演示其安装与使用方法…

    2026年5月10日
    000
  • JavaScript计算器开发:解决数值显示与初始化问题

    本教程深入探讨了使用JavaScript构建计算器时常见的数值显示异常问题,特别是由于类属性未初始化导致的`Cannot read properties of undefined`错误。我们将详细分析问题根源,并通过在构造函数中调用初始化方法来解决该问题,同时优化显示逻辑,确保计算器功能稳定且界面显…

    2026年5月10日
    000
  • NextAuth getToken 在服务端返回 null 的问题排查与解决

    问题描述 在使用 Next.js 和 NextAuth 构建应用程序时,有时需要在服务端获取用户的身份验证信息。getToken 函数是 NextAuth 提供的一个便捷方法,用于从请求中提取 JWT (JSON Web Token)。然而,在某些情况下,尤其是在使用 getServerSidePr…

    2026年5月10日
    000
  • HTML表单如何实现PWA支持?怎样添加离线功能?

    答案是利用Service Worker缓存资源并结合Background Sync API实现离线提交与自动同步。通过注册Service Worker缓存表单相关文件,拦截提交行为,将离线数据存入IndexedDB,并注册后台同步任务,待网络恢复后由Service Worker自动发送数据,确保提交…

    2026年5月10日
    000
  • HTML文档如何工作?如何编辑HTML格式文件?

    HTML文档如何工作?如何编辑HTML格式文件?HTML文档如何工作?如何编辑HTML格式文件?HTML文档如何工作?如何编辑HTML格式文件?HTML文档如何工作?如何编辑HTML格式文件?

    浏览器解析和渲染html的过程包括:1. 解析html构建dom树;2. 结合css构建渲染树;3. 布局计算元素位置;4. 绘制像素到屏幕。编辑html可使用记事本、vs code、sublime text等文本或代码编辑器,其中vs code因语法高亮、自动补全和插件生态成为主流选择。标准htm…

    2026年5月10日 用户投稿
    000

发表回复

登录后才能评论
关注微信