I have a problem when I try to get images from .json file in react, path is ok, also all other data are displayed with no problem, image take space and link can be seen in inspect but image itself is not shown. I have try literally everything I can do, images imported in classic way work fine (direct import not from .json file).
My code:
// import demo from "../../assets/icons/demo.jpg";
// import metalPan from "../../assets/icons/metalPan.jpg";
// import Foodie from "../../assets/icons/Foodie.jpg";
import "./Projects.scss";
import ProjectData from "../../json/projects.json";
function Projects() {
return (
<>
<h2 className="section_name">Projects</h2>
<div className="projects">
{/* Project card */}
{ProjectData?.map((info) => {
return (
<>
<div key={info?.id} className="project_wrraper">
<div className="project">
<h3 className="project_name">{info.name}</h3>
<div className="project_tech">
{info.stack.map((data) => {
return (
<div>
<span>{data.language}</span>
</div>
);
})}
</div>
<p className="project_descr">{info.description}</p>
<div className="project_stack">
<button className="stack-btn">Live version</button>
<button className="stack-btn">GitHub</button>
</div>
</div>
<img
className="project_img"
src={`${info.image}`}
alt=""
/>
</div>
</>
);
})}
{/* end of project card */}
</div>
</>
);
}
export default Projects;
[
{
"id": 1,
"name": "Metal Pan",
"stack": [
{"language": "JavaScript"},
{"language": "Sass"},
{"language": "BootStrap"},
{"language": "PHP"}
],
"image": "../assets/icons/metalPan.jpg",
"description": "Web Site made for company specialized in manufacturing and setting up industrial halls and metal roofs."
},
{
"id": 2,
"name": "Foodie",
"stack": [
{"language": "JavaScript"},
{"language": "Sass"},
{"language": "HTML5"}
],
"image": "../assets/icons/Foodie.jpg",
"description": "Personal project of responsive restaurant design with gallery, blog and menu!"
},
{
"id": 3,
"name": "eShop",
"stack": [
{"language": "React"},
{"language": "CSS"},
{"language": "HTML5"}
],
"image": "../assets/icons/eShop.jpg",
"description": "Personal project of eShop store using fake api, fetch all data, single product data and filter function."
}
]
I have tried to use many solutions but no luck some I will provide here (just to name few):
React, load images local from json
https://www.appsloveworld.com/reactjs/100/33/get-local-image-path-from-json-in-react
Are the images inside the public folder? The problem is very clearly that the image src is a relative path, but react will try to look them up in your public folder. If you replace the value of the images from "image": "../assets/icons/Foodie.jpg" to "image": "/assets/icons/Foodie.jpg" I think it should work.
You can solve this problem by following this approach-
Create a folder of any name (the recommended name would be assets or images) in the public directory.
So, the path to the image would be folderName/image.jpg.
So no matter what the absolute path is, it doesn't target the public folder.
Also if images are in the src folder you can't add them to the src tag. Just import it and that is why import work but the .json path doesn't.
Check out this SO solution, you may need to incorporate the require('../assets/...'); within your map function.
so it looks something like this.
<img className="project_img" src={require(${info.image})} alt=""/>
Related
i'm learning javascript and React JS but i got a problem when i want to fetch some information on the Pokemon API ^^ I can fetch some information but i want to get the second types of Pokemon, as you can see, it's working for the first type but not the second.
I think the problem is that not all the pokemon got 2 types ("apiTypes"), but i don't know how to render the second one. Thanks for your helping and sorry for my english ;)
The JSON : https://pokebuildapi.fr/api/v1/pokemon
/ https://pokebuildapi.fr/api/v1/pokemon
[
{
"id": 1,
"pokedexId": 1,
"name": "Bulbizarre",
"image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
"slug": "Bulbizarre",
"stats": {
"HP": 45,
"attack": 49,
"defense": 49,
"special_attack": 65,
"special_defense": 65,
"speed": 45
},
"apiTypes": [
{
"name": "Poison",
"image": "https://static.wikia.nocookie.net/pokemongo/images/0/05/Poison.png"
},
{
"name": "Plante",
"image": "https://static.wikia.nocookie.net/pokemongo/images/c/c5/Grass.png"
}
],
import React from 'react';
const Card = ({pokemon}) => {
return (
<li className='card'>
<img src={pokemon.image} />
<h3>#{pokemon.id} {pokemon.name}</h3>
<div className='infos'>
<img src={pokemon.apiTypes[0].image}/>
<img src={pokemon.apiTypes[1].image}/>
</div>
</li>
);
};
export default Card;
I know i have to ask if there is an image on [1], but i don't know how...
thanks a lot :)
One way to solve this is to iterate over all apiTypes using the map method, like this:
import React from 'react';
const Card = ({pokemon}) => {
return (
<li className='card'>
<img src={pokemon.image} />
<h3>#{pokemon.id} {pokemon.name}</h3>
<div className='infos'>
{
pokemon.apiTypes.map( apiType => <img src={apiType.image}/>
}
</div>
</li>
);
};
export default Card;
you've mentioned, not all pokemon have two types, so trying to access the second type using pokemon.apiTypes[1] would result in an error for those pokemon that only have one type.
One way to fix this issue would be to only render the second type image if it exists. You can do this by checking the length of the apiTypes array, and only rendering the second type image if the length is greater than 1.
import React from 'react';
const Card = ({pokemon}) => {
return (
<li className='card'>
<img src={pokemon.image} />
<h3>#{pokemon.id} {pokemon.name}</h3>
<div className='infos'>
<img src={pokemon.apiTypes[0].image}/>
{pokemon.apiTypes.length > 1 && <img src={pokemon.apiTypes[1].image}/>}
</div>
</li>
);
};
export default Card;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I have an array of objects that looks like this:
export const NGOarray = [
{
name: "1% for the Planet ",
description:
"A leading global nonprofit, building a movement of businesses and individuals delivering philanthropic support to environmental organizations working on the front lines for our planet.",
link: "https://onepercentfortheplanet.org/",
category: ["water", "everything"],
logo: "1fortheplanet.webp",
},
{
name: "4ocean",
description:
"As both a public benefit corporation and Certified B Corp, we’re committed to ending the ocean plastic crisis.",
link: "https://www.4ocean.com",
category: ["water", "everything"],
logo: "4 Ocean.svg",
} ]
The logo property maps to the filename they have in a folder.
I'm trying to map through that array and show each image like this:
{NGOarray.map((org) => {
<div key={org.name}>
{org.logo && (
<img
src={
require(`../assets/organizations/${org.logo}`)
.default
}
/>
)}
<h3 className="text-2xl font-sans mb-4">{org.name}</h3>
<p>{org.description}</p>
</div>
);
}
But the image won't show up.
Any idea how I can get it to work?
Okay, this seems to have worked, leaving answer here for reference:
function importAll(r) {
return r.keys().map(r);
}
const logos = importAll(
require.context("../assets/organizations/", false, /\.(png|jpe?g|svg)$/)
);
And when mapping the array:
{NGOarray.map((org, index) => {
<div key={org.name}>
{org.logo && <img src={logos[index]} alt={org.name} />}
<h3 className="text-2xl font-sans mb-4">{org.name}</h3>
<p>{org.description}</p>
</div>
);
}
I've been trying to learn React over the past few weeks, and have decided to go through the LamaDev tutorial series. Yesterday I started with the portfolio tutorial (https://www.youtube.com/watch?v=hQjlM-8C4Ps&t=2798s) but have been stuck with trying to load images in my array.
I went ahead and built a component called 'Product' which the code can be found below. After that I followed the instructions and built the ProductList component which is suppose to show each of my products that are in my data.js file. I have gone and posted those below.
The problem I am running in to is that if I use a random img link from the internet the image gets imported into my product and show through my product list. However this is not what I am wanting to do since there are some images of my own I wanted to use.
When my Product.jsx tried to use a image I have saved in src/assets/img/ the img won't load. I tried using the require tag but it still is not working. I have also gone ahead and uploaded everything to my github page which can be found here and used as a reference.
I'm really not sure what I've done wrong here since everything looks right, but still know the issue is falling between the keyboard and the chair.
Thanks for any help
Product.jsx
import "./product.css";
const Product = ({ img, link }) => {
return (
<div className="p">
<div className="p-browser">
<div className="p-circle"></div>
<div className="p-circle"></div>
<div className="p-circle"></div>
</div>
<a href={link} target="_blank" rel="noreferrer">
<img src={img} alt="" className="p-img" />
</a>
</div>
);
};
export default Product;
ProductList.jsx
import Product from "../product/Product";
import "./productList.css";
import { products } from "../../data";
const ProductList = () => {
return (
<div className="pl">
<div className="pl-texts">
<h1 className="pl-title">Create & inspire. It's Jon</h1>
<p className="pl-desc">
Jon Snow is a creative portfolio that your work has been waiting for.
Beautiful homes, stunning portfolio styles & a whole lot more awaits
inside.
</p>
</div>
<div className="pl-list">
{products.map((item) => (
// console.log(item)
<Product key={item.id} img={item.img} link={item.link} />
))}
</div>
</div>
);
};
export default ProductList;
data.js
export const products = [
{
id: 1,
img: require("./assets/img/theBestTestSite.jpg"),
link: "http://google.com",
},
{
id: 2,
img: require("./assets/img/theBestTestSite.jpg"),
link: "http://google.com",
},
{
id: 3,
img: require("./assets/img/theBestTestSite.jpg"),
link: "http://google.com",
},
];
In data.js try to import images first instead of require
import img1 from "./assets/img/theBestTestSite.jpg"
export const products = [
{
id: 1,
img: img1,
link: "http://google.com",
},
// and same for others
];
I currently creating a react app of e-commerce, I am stuck with a feature where when the product clicks and redirects to the product details page, I successfully can get the product image and the details using props but can't get the product image. The product image needs a call from an API. So I try to direct call from the src. But I getting the error of the Module not being found. Plz, help me with this.
Getting an error in the code in this line where I try to call the API directly tp src.
This is the error I'm getting
// carousel items
const carouselItems = [
{
src: require(`/api/v1/ProductFile/${encodeURIComponent(
data.data.ID
)}/Product/${encodeURIComponent(
data.data.ProductImages[0]
)}`),
altText: "Somewhere",
caption: "Somewhere",
},
{
src: require("assets/img/megan-product-2.jpg"),
altText: "Somewhere else",
caption: "Somewhere else",
},
{
src: require("assets/img/megan-product-3.jpg"),
altText: "Here it is",
caption: "Here it is",
},
{
src: require("assets/img/megan-product-4.jpg"),
altText: "Here it is",
caption: "Here it is",
},
];
<div>
<Row>
<Col key={data.data.ID} md="7" sm="6">
<div className="ml-auto mr-auto" id="carousel">
<Card className="page-carousel">
<Carousel
activeIndex={activeIndex}
next={next}
previous={previous}
>
<CarouselIndicators
items={carouselItems}
activeIndex={activeIndex}
onClickHandler={goToIndex}
/>
{carouselItems.map((item) => (
<CarouselItem
onExiting={onExiting}
onExited={onExited}
key={item.src}
>
<img src={item.src} alt={data.data.Name} />
<CarouselCaption captionHeader={data.data.Name} />
</CarouselItem>
))}
</Carousel>
</Card>
</div>
{/* end carousel */}
</Col>
</Row>
</div>
thanks, I have solved it by just remove the require word.
You should remove require() wrapping the API URL.
The error is telling you that the file path does not exist.
Each item in the Carousel uses an <img> that takes an src attribute. To use an API endpoint/URL for the src, it should be passed directly as a string without using require.
I have an application in React where I'm trying to read in data from a JSON file. The JSON file is in the following format:
[
{
"name": "Max",
"age": "21",
},
{
"name": "Sam",
"age": "18",
}
........
]
I have successfully read in the right data and displayed it on my screen, like this:
function foo(){
const styling = css`
font-size: 30px;
`;
return(
<div>
{people.map((person, i) => <Format key={i} {...person} css={styling}/>)}
</div>
);
}
Although all the information correctly displays on the screen, the styling is not getting applied to each person. How could I change this?
EDIT
Format component:
function Format({name, age}){
return (
<div>
<h1>{name}</h1>
<h2>{age}</h2>
</div>
);
}
function Format({name, age, css}){
return (
<div css={css}>
<h1>{name}</h1>
<h2>{age}</h2>
</div>
);
}
you passed styled to your component but you didnt use them in your child component
and plus using idx as key is not the best practice. following article explains why.
https://reactjs.org/docs/lists-and-keys.html
if name is unique you can pass each items name to mapped children.