I made a JavaScript database inside my React project with a couple of dishes. Example:
It contains a name, image, national flag, and a YouTube video ID.
{
id: 23,
name: "Beef Stir Fry",
type: "Main Course",
origin: "China",
flag: { flagChina },
image: "../assets/image/food/beefstirfry.jpg",
alt: "Chinese Beef Stir Fry",
ingredients: [
"Beef sirloin",
"Garlic",
"Ginger",
"Green onions",
"Red bell pepper",
"Soy sauce",
"Oyster sauce",
"Cornstarch",
"Sesame oil",
"Vegetable oil",
"Salt",
"Black pepper",
],
preparation: [
"Cut the beef into thin strips, and season with salt, black pepper, and cornstarch.",
"In a wok or large skillet, heat the vegetable oil over high heat.",
"Add the beef to the pan and cook for about 2-3 minutes, or until browned.",
"Remove the beef from the pan and set it aside.",
"In the same pan, add the garlic, ginger, and green onions and stir-fry for about 30 seconds, or until fragrant.",
"Add the red bell pepper to the pan and continue stir-frying for another minute.",
"Return the beef to the pan, and add soy sauce, oyster sauce, and sesame oil.",
"Stir everything together until the beef and vegetables are coated in the sauce and heated through.",
"Serve hot over rice or noodles.",
],
ytID: "cyS8ycmGs1U",
},
Inside my main page file, I have a grid with buttons that each resemble the recipes. How can I create a pop-up showing this particular information from the database for the right recipe in my main page after a recipe button is clicked?
I have already tried to experiment with making a template file, and importing the database in that template file, but I am at a loss on how to continue even further.
Current main page, already has a function that allows the user to search for a recipe, type, or the country it originates from.
return (
<>
<section>
<div className="searchbar">
<input
style={{ backgroundImage: `url(${magGlass})` }}
type="text"
value={search}
placeholder="...Search Recipe"
onChange={(search) => setSearch(search.target.value)}
/>
</div>
<div className="recipe-grid">
{recipeFilter.map((recipe) => (
<Recipe
key={recipe.dish}
title={recipe.title}
type={recipe.type}
img={recipe.img}
alt={recipe.alt}
flag={recipe.flag}
/>
))}
</div>
</section>
</>
);
};
export default Browser;
I have made a template file by importing the foods database in there and creating entries such as {foods.name}, {foods.ingredients}, but I cannot verify if it works at all. I've tried creating something with stories, but stories couldn't load my file, so I am kinda confused on how to get this to work.
Related
My navigation links work in my app and on my homepage but when I try to create a button link to my product page from my shop its either only showing the header and footer (which are in my app.js file or showing a blank screen. Ive imported the product page at the top so I dont understand why it isnt working. Any help would be much appreciated. Below is my shop.js file
import React, { useState } from 'react';
import AddToCart from './Components/AddToCart';
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Product from './Product';
const HOME_GARDEN = 'home and garden';
const ART = 'Art';
const ACCESSORIES = 'Accessories';
const DIGITAL_PHOTOGRAPHS = 'Digital Photographs';
const FASHION = 'Fashion';
const FOOTWEAR = 'Footwear';
const JEWELLERY = 'Jewellery';
const ALL = 'All';
export default function Shop({ setCart, cart, handleClick }) {
const [products] = useState([
{
category: ART,
name: 'Original David Bowie Mug Shot Mixed Media Framed Artwork',
cost: 200,
image:'images/bowiebig.jpeg',
image2: 'images/bowiesmall.jpeg',
image3:'images/bowie2small.jpeg',
description: "Original David Bowie Mug Shot Mixed Media Framed Artwork floral
painting on wooden canvas with an original pop art style David Bowie Mugshot on top
painting is framed with a red baroque style frame including the words deadly flowers
bloom around frame",
},
{
category: ACCESSORIES,
name: 'F&F Ladies Long Black Real Leather Size Small Gloves',
cost: 35,
image:'images/Fred.jpeg',
image2: '',
image3:'',
description: 'F&F Ladies Long Black Real Leather Size Small Gloves with ruched
horizontal detailing on the front. Gloves are in good condition ',
},
{
category: DIGITAL_PHOTOGRAPHS,
name: 'Black on Black Original Limited Edition Digital Photograph',
cost: 50,
image:'images/BlackonBlack.jpg',
image2: '',
image3:'',
description: 'Upon purchase you will receive links to download the digital
photograph in the thank you page of the checkout as well as an emailed link that
will last 30 days. ',
},
{
category: FASHION,
name: 'Ladies Small BOY London Distressed Acid Wash Blue Midi Denim Skirt',
cost: 50,
image:'images/Boy.jpeg',
image2: '',
image3:'',
description: 'Ladies Small BOY London Distressed Acid Wash Blue Midi Denim
Skirt. BOY London sizes run small. This skirt is size 8/10 even though the label
says large. Condition is New with tags.',
},
{
category: FOOTWEAR,
name: 'Ladies Size 8 / 41 Black Real Suede Jeffrey Campbell Platform Open
Toe Sandals',
cost: 60,
image:'images/Campbell.jpeg',
image2: '',
image3:'',
description: 'Ladies UK Size 8 European size 41 black real suede Jeffrey
Campbell high platform open-toe sandals with adjustable strap. The sandals are in
good condition as theyve only worn outside a few times. The heel and platform is
made from wood so the sandals are sturdy but relatively lightweight. ',
},
{
category: JEWELLERY,
name: 'Jean Paul Gaultier Scandal Bottle Top Customised Fishnet
Necklace',
cost: 50,
image:'images/Scandal.jpeg',
image2: '',
image3:'',
description: 'Jean Paul Gaultier Scandal Bottle Top Customised Necklace
made with braided fishnets.',
},
{
category: HOME_GARDEN,
name: 'Blanket',
cost: 19.99,
image:
'https://encrypted
tbn0.gstatic.com/imagesq=tbn%3AANd9GcSpwdYDmUL_ZEqhL
V7ZWRdQAU7DGcGaxtCt7SrTlL9umrQs2Un7rj9Nbb9Vq01RtEfA0eAVmdt-&usqp=CAc',
page:'Blanket',
},
]);
const [category, setCategory] = useState(ALL);
const getProductsInCategory = () => {
if (category === ALL) {
return products;
} else {
return products.filter((product) => product.category === category);
}
};
return (
<>
<h1>Shop</h1>
<button onClick={(e) => setCategory(ART)}>
Art</button>
<button onClick={(e) => setCategory(HOME_GARDEN)}>
Home and Garden</button>
<button onClick={(e) => setCategory(ACCESSORIES)}>
Accessories</button>
<button onClick={(e) => setCategory(DIGITAL_PHOTOGRAPHS)}>
Digital Photographs</button>
<button onClick={(e) => setCategory(FASHION)}>
Fashion</button>
<button onClick={(e) => setCategory(FOOTWEAR)}>
Footwear</button>
<button onClick={(e) => setCategory(JEWELLERY)}> Jewellery</button>
<button onClick={(e) => setCategory(ALL)}>
All</button>
<div className="products">
{getProductsInCategory().map((product, idx) =>(
<div className="product" key={idx}>
<h3>{product.name}</h3>
<h4>£{product.cost}</h4>
<img src={product.image} alt={product.name} />
<br />
<AddToCart product={product} cart={cart} setCart={setCart}/>
<Link to="/Product"><button type="button">Product</button></Link>
<Routes>
<Route path="/Product" element={<Product />} />
</Routes>
<button onClick={() => handleClick(product)}>
View Product
</button>
</div>
))}
</div>
</>
);
}
I have a JSON file in the public folder and would like to use the data throughout the react app. I'm using axios in App.js but don't know the best way to store the data received in the state. I was going to use props but there is a lot of data being returned so that's probably not the best idea. So I thought of using axios in each component (Home, About, Posts, Footer, and Aside) but that wouldn't make sense either because data is meant to flow from app.js to children, and I don't want to repeat code. This led me to google search for solutions using Redux, I haven't come across any potential articles or videos explaining how to use Axios with Redux. My question is is there a way to manage JSON data in Redux or another state management library?
App.js
function App() {
const [data, setData] = useState({});
useEffect(() => {
axios.get('data/data.json')
.then(res => setData(res.data))
.catch(err =>console.log(err))
},[])
return (
<Router>
<header>
<div className="container container-flex">
<div className="site-title">
<h1>{data.title}</h1>
<p className="subtitle">{data.subtitle}</p>
</div>
<nav>
<ul>
<li><Link className="current-page" to="/">home</Link></li>
<li><Link to="/about">about me</Link></li>
<li><Link to="/posts">recent posts</Link></li>
</ul>
</nav>
</div>
</header>
<div className="container container-flex">
<Routes>
<Route path="/" element={<Home />}/>
<Route path="/about" element={<About />}/>
<Route path="/posts" element={<Posts />}/>
<Route path="*" element={<Error />}/>
</Routes>
<Aside />
</div>
<Footer/>
</Router>
);
}
export default App;
HOME.js
const Home = () => {
// const [data, setData] = useState({});
// useEffect(() => {
// axios.get('data/data.json')
// .then(res => setData(res.data))
// .catch(err =>console.log(err))
// },[])
// console.log(data.articlemain1.title)
return (
<>
<main role="main">
<article className="article-featured">
<h2 className="article-title">{articleman1.title}</h2>
<img className="article-image" src={articleman1.image} alt={articleman1.alt}/>
<p className="article-info">{articleman1.info}</p>
<p className="article-body">{articleman1.body}</p>
<a className="article-read-more" href="https://www.github.com/jerrellbryant"></a>
</article>
<hr>
</hr>
</main>
</>
)
}
export default Home
Data.json
{
"title": "Living the simple life",
"subtitle": "a blog exploring minimalism in life",
"articlemain1": {
"title": "Finding simplicity in life",
"image": "img/life.jpg",
"alt": "Clock plant and lamp on a desk",
"info": "Feburary 21, 2022",
"body": "\n <strong>Life can get complicated really quickly</strong>, but it doesn't have to be!\n There are many ways to simplify your life, <a class='article-link' href='#'> a few of which we've explored in the past</a>.\n This week we're taking a bit of a approach though, in how you can find simplicity in the life you already living.",
"anchor": "Continue Reading"
},
"articlesecondary1": {
"image": "img/life.jpg",
"alt": "Clock plant and lamp on a desk",
"info": "Feburary 21, 2022",
"comments": "3 comments"
},
"articlemain2": {
"title": "Keeping cooking simple",
"body": "\n Food is a very important part of everyone's life.\n If you want to be healthy, you have to eat healthy.\n One of the easiest ways to do that is to keep your cooking nice and simple.",
"anchor": "Continue Reading"
},
"articlesecondary2": {
"image": "img/food.jpg",
"alt": "dumplings with chop sticks",
"info": "July 12, 2021",
"comments": "5 comments"
},
"articlemain3": {
"title": "Simple decoractions",
"body": "\n A home isn't a home until you've decorated a little.\n People either don't decorate, or they go overboard and it doesn't have the impact they were hoping for. \n Staying simple will help draw the eye where you want it to and make things pop like never before.",
"anchor": "Continue Reading"
},
"articlesecondary3": {
"image": "img/deco.jpg",
"alt": "plant in water bowl",
"info": "June 15, 2021",
"comments": "9 comments"
},
"articlemain4": {
"title": "Simplicity and work",
"body": "\n Work is often a major source of stress.\n People get frustrated,it ruins their relationship with others and it leads to burnout. \n By keeping your work life as simple as possible, it will help balance everything out.",
"anchor": "Continue Reading"
},
"articlesecondary4": {
"image": "img/work.jpg",
"alt": "desk chair with a white table",
"info": "May 7, 2021",
"comments": "6 comments"
},
"widgettitle1": "About Me",
"widgettitle2": "Recent Posts",
"image": "img/aboutme.jpg",
"alt": "author smiling",
"body": "I find life better, and I'm happier, when things are nice and simple.",
"widgetpost1": {
"title": "Keeping cooking simple",
"image": "img/food.jpg"
},
"widgetpost2": {
"title": "Simplicity and work",
"image": "img/work.jpg",
"alt": "dumplings with chop sticks"
},
"widgetpost3": {
"title": "Simple decorations",
"alt": "plant in water bowl",
"image": "img/deco.jpg"
},
"footer": {
"website": "Living the Simple Life",
"copyright": "Copyright 2022"
}
}
You could move the JSON out of the public folder and just import it into your app.
If you want to do it in redux using axios then having an action handle the API call is the best way to do it.
I would also look at replacing axios with fetch as it will save you an import or two.
I have a dummy testimonials.I want to display it as a slider.
I am using React-Bootstrap but I am not able to get the desired result.
Here is the code.
const testimonial: [
{
content:
'Over all though it was a great experience and we have had lots of great feedback. We already started promoting our next event and I have been approached by 4 other companies who want to know more about it as they want to use it for their own events.',
author: 'Sarah M., Director of Events',
},
{
content:
'I cannot tell you how much we loved using this silent auction software. Everything was seamless…from set up, to bidding, to payment. We will absolutely use MyEvent next year.',
author: 'Sarah M., CCHS Foundation',
},
{
content:
"I tried MyEvent instead of typical paper raffle tickets. The system was easy to set up online and people who couldn't attend the event were still able to enter the raffle, which was HUGE bump in revenue.",
author: 'Alexander B., Pan-Mass Challenge',
},
{
content:
'MyEvent is a great way to bring in money for your Fund A Need. The 24/7 tech support allows you to feel confident, and the platform makes your Fund a Need so much easier to run. Well definitely be using MyEvent again.',
author: 'Amy C., One Less Orphan Fund',
},
]
testimonial.map((item, index) => (
<div key={index}>
{ item.content && (
<div className="aceele-infos" key={index}>
<Carousel>
<Carousel.Item>
<Carousel.Caption>
<span className="signup-infos">{`"${item.content}"`}</span>
<div className="awnor-infos">
<span className="signup-infos">
{`-`}
{item.author}
</span>
</div>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</div>
But I am not getting the result how I want.
Here is an image how I want.
You need to map over your Carousel Items and not the entire div because you only want the carousel items to repeat inside the carousel and not the entire carousel.
Your return statement would look something like this:
<div>
<Carousel interval={1000}>
{testimonial.map((c, index) => {
return (
<Carousel.Item interval={5000}>
<div style={{ height: 500, background: "black", color: "white" }}>
<p>{c.content}</p>
</div>
<Carousel.Caption>
<p>{c.author}</p>
</Carousel.Caption>
</Carousel.Item>
);
})}
</Carousel>
</div>
I also have a working example for you in codesandbox below
https://codesandbox.io/s/interesting-aryabhata-qsb9g?file=/src/App.js:1332-1796
I am trying to use a slide that shows products attributes in my app.
The products variable has the ID, NAME, DESCRIPTION, PRICE and IMAGE.
const products = [{
id: 1,
name: "Sapato1",
description: "comfort line with adaptive design",
price: "999,99",
img: "../img/hamburger1.jpg"
}, {
id: 2,
name: "Product X",
description: "Different sizes and shapes",
price: "999,99",
img: "../img/hamburger2.jpg"
}, {
id: 3,
name: "Product Y",
description: "Many different features",
price: "999,99",
img: "../img/hamburger3.jpg"
}]
Using HTML img tag with an import it is working, but I would like to have the image related to the product I am showing, as variable.
import Image from '../img/hamburger1.jpg';
<img src={Image} alt="produt1" />
but I would like to use src={product.img} instead of the src={Image} but it is not working.
This is the code I am using
{products.map((product) =>
<IonSlide>
<IonCard button={true}>
<IonCardHeader>
<IonCardTitle>{product.name}</IonCardTitle>
<IonCardSubtitle>Card Subtitle</IonCardSubtitle>
</IonCardHeader>
<IonCardContent>
<img src={Image} alt="produt1" />
{product.description}
</IonCardContent>
<IonButton expand="full" href="#" color="primary"><IonIcon slot="start" icon={cart} />R$ {product.price}</IonButton>
</IonCard>
</IonSlide>
)}
You should put your img folder along with all the pictures in the public folder. And then you can change your references to the images like img: "/img/hamburger1.jpg". That should work. Here's a working example - https://codesandbox.io/s/hungry-golick-funtz?file=/src/App.js
I have successfully changed the state using NASA's api.
Now I would like to display title, image and explanation from the api. I'm a beginner so go easy on me!
I have tried searching and trying different code to no prevail. Wondered if someone on here could shine light on what I have been doing wrong.
this.state = {
picture: "",
date: ""
};
componentDidMount(){
fetch(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`)
.then(response => response.json())
.then(json => this.setState({ picture: json }));
};
render(){
return (
<div className="container">
<h1>NASA Picture of the Day</h1>
<form onSubmit={this.handleSubmit}>
(YYYY-MM-DD):
<input
type="text"
id="date"
placeholder="input date"
value={this.state.date}
onChange={this.handleChange}
/>
<button type="submit" disabled={!this.state.date}>
Submit
</button>
</form>
</div>
);
};
Currently a sample response from NASA API is as below: ( NOt sure if it changes in future)
{
"date": "2019-08-04",
"explanation": "Twenty-one years ago results were first presented indicating that most of the energy in our universe is not in stars or galaxies but is tied to space itself. In the language of cosmologists, a large cosmological constant -- dark energy -- was directly implied by new distant supernova observations. Suggestions of a cosmological constant were not new -- they have existed since the advent of modern relativistic cosmology. Such claims were not usually popular with astronomers, though, because dark energy was so unlike known universe components, because dark energy's abundance appeared limited by other observations, and because less-strange cosmologies without a signficant amount of dark energy had previously done well in explaining the data. What was exceptional here was the seemingly direct and reliable method of the observations and the good reputations of the scientists conducting the investigations. Over the two decades, independent teams of astronomers have continued to accumulate data that appears to confirm the existence of dark energy and the unsettling result of a presently accelerating universe. In 2011, the team leaders were awarded the Nobel Prize in Physics for their work. The featured picture of a supernova that occurred in 1994 on the outskirts of a spiral galaxy was taken by one of these collaborations. News: APOD is now available via Facebook in Hindi.",
"hdurl": "https://apod.nasa.gov/apod/image/1908/SN1994D_Hubble_2608.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Rumors of a Dark Universe",
"url": "https://apod.nasa.gov/apod/image/1908/SN1994D_Hubble_960.jpg"
}
To display some information from NASA in the same component (Assuming you want to display details before your submit button click)
let picture = this.state.picture;
return (
<div className="container">
<h1>NASA Picture of the Day</h1>
<h2>{picture.title}</h2>
<img src={picture.url} alt={picture.title}></img>
<p>{picture.explanation}</p>
___________ YOUR FORM INPUT CONTROLS _____________
</div>
);
You're not using this.state.picture anywhere. Simply use whatever data is there to render your image.
I'm not sure what format the data is in but assuming the API returns JSON like:
{ "url": "http://nasa.gov/path/to/image.png" }
Then you just need this somewhere:
{ this.state.picture && <img src={this.state.picture.url} /> }
As you stored data in picture , write this in render
return (<ul>this.pictureToDisplay()</ul>)
pictureToDisplay definition :- (Assuming this to be an array of pictures)
return (this.state.picture.map(item=><li>item</li>))
You can do it this way. Just use a different component for the api data and render it conditionally.
this.state = {
picture: "",
date: ""
};
componentDidMount(){
fetch(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`)
.then(response => response.json())
.then(json => this.setState({ picture: json }));
};
render(){
let picture_data = this.state.picture;
return (
<div className="container">
<h1>NASA Picture of the Day</h1>
<form onSubmit={this.handleSubmit}>
(YYYY-MM-DD):
<input
type="text"
id="date"
placeholder="input date"
value={this.state.date}
onChange={this.handleChange}
/>
<button type="submit" disabled={!this.state.date}>
Submit
</button>
</form>
{picture !== "" ? <DataComponent picture={picture} />:<div/>}
</div>
);
};
Your Child Component for showing the Nasa's data. Change your Json from api accordingly I used some random keys.
import React, { Component } from 'react';
class DataComponent extends Component {
render() {
let picture = this.props.picture;
return ( <div>
<h1>{picture.someHeading}</h1>
<img src={picture.someURL}></img>
<p>{picture.someDecription}</p>
</div> );
}
}
export default DataComponent;