I've got a problem with showing image from js file. I really dont know what i can do with that. Can someone help me?
Code for main component:
import React from 'react'
import {jetData} from '../jetData'
const MainBar = () => {
return (
<div className='text-white'>
{jetData.map((data, key) => {
return (
<div key={key}>
{<img src={data.image} /> + data.name}
</div>
);
})}
</div>
)
}
export default MainBar
Code for js file with data:
import f18 from './assets/jets/f-18cd-hornet.png'
import f22 from './assets/jets/f-22-raptor.png'
import mig29 from './assets/jets/mig-29.png'
import su27 from './assets/jets/Sukhoi_Su-27SKM.png'
export const jetData = [
{
image: {f18},
name: 'F/A-18 Hornet'
},
{
image: {f22},
name: 'F-22 Raptor'
},
{
image: {mig29},
name: 'MiG-29'
},
{
image: {su27},
name: 'Su-27'
},
]
Check if this works i hope it will work sorry at this point i can not run it for you
return (
<div className="text-white">
{jetData.map((jet) => (
<div key={jet.id}>
<img src={jet.image} alt={jet.name} />
</div>
))}
</div>
);
I think what you are trying to do is this:
import logo from './logo.svg';
<img src={logo} className="App-logo" alt="logo" />
Which works fine with .svg files, but not with .jpg and .png. The reason seems to be that import logo from './logo.svg'; stores the path in the variable, but import f18 from './assets/jets/f-18cd-hornet.png stores a, what to me looks like, a string representation of the image.
I think this is the way to go:
export const jetData = [
{
image: './assets/jets/f-18cd-hornet.png',
name: 'F/A-18 Hornet'
}]
Your imports do not need to be in curly braces:
import f18 from './assets/jets/f-18cd-hornet.png'
import f22 from './assets/jets/f-22-raptor.png'
import mig29 from './assets/jets/mig-29.png'
import su27 from './assets/jets/Sukhoi_Su-27SKM.png'
export const jetData = [
{
image: f18,
name: 'F/A-18 Hornet'
},
{
image: f22,
name: 'F-22 Raptor'
},
{
image: mig29,
name: 'MiG-29'
},
{
image: su27,
name: 'Su-27'
},
]
Your map key will likely throw an error because you are using the index as a key. I would change it to the following
{jetData.map((data) => {
return (
<div key={data.name}>
<img src={data.image} alt={data.name} />
</div>
);
})}
Related
My image is not showing in React app. I am trying to fetch the path from JSON and pass the path using props in <img> tag.
Example JSON object with the product data:
let data = [
{
id: 1,
name: "Striped Slim Fit Shirt",
image: "./Assets/m1.jpg",
price: 1000,
category: "Men",
size: "XL",
inStock: true,
},
{
id: 2,
name: "Full Sleeves Slim Fit Shirt",
image: "./Assets/m2.jpg",
price: 2000,
category: "Men",
size: "L",
inStock: true,
},
];
export default data;
My parent component from which I am passing props.
import { Fragment } from "react";
import data from "../../DUMMY_DATA";
import ItemList from "./ItemList";
const HomePage = () => {
const availableItems = data.map((products) => (
<ItemList
key={products.id}
images={products.image}
name={products.name}
price={products.price}
category={products.category}
size={products.size}
/>
));
return (
<Fragment>
<div>{availableItems}</div>
</Fragment>
);
};
export default HomePage;
My child component. Here, console logging shows the correct path, but the <img> tag is not rendering it.
import { Fragment } from "react";
const ItemList = (props) => {
const { id, images, name, price, category, size, inStock } = props;
return (
<Fragment>
<div className="container text-center">
<div className="row row-cols-4" key={id}>
<div className="col">
<img src={images} />
</div>
<div className="col">{name}</div>
<div className="col">{size}</div>
<div className="col">{price}</div>
</div>
</div>
</Fragment>
);
};
export default ItemList;
I'm trying to render a Card component dynamically mapped from an array of objects.
The issue is I'm getting an "unexpected token error ..." And URL won't render. I should see five cards display based on the data inside the array, but it throws an error. Does anyone see where I'm going wrong? I'm using React 18 if that matters.
Component code:
import React from "react";
import links from "../links";
function Card (props) {
return (
<div>
<div className="link-container">
<div className="row">
<div className="card">
<hr className="divide"></hr>
<img className="img" src={props.img} alt="social-icon" />
<h4>{props.name}</h4>
</div>
</div>
</div>
</div>
)
}
Data:
const links = [
{
id: 1,
name: "Youtube",
img:"./img/youtube.svg",
href: "https://www.youtube.com/c/SubwaySounds"
},
{
id: 2,
name: "Spotify",
img:"./img/spotify.svg",
href: "https://artists.spotify.com/c/artist/3DM32kjsG7Pp5EM7o3Uv7t/profile/overview"
},
{
id: 3,
name: "Tiktok",
img:"./img/tiktok.svg",
href: "https://www.tiktok.com/#nysubwaysounds"
},
{
id: 4,
name: "Instagram",
img:"./img/instagram.svg",
href: "https://www.instagram.com/nycsubwaysounds/?hl=en"
},
{
id: 5,
name: "Shop",
img:"./img/shop.svg",
href: "https://my-store-11524143.creator-spring.com/"
}
]
export default links;
App.jsx:
import Header from "./Header";
import Card from "./Card";
import links from "../links";
function CreateCard (socialLinks) {
return (
<Cards
key= {socialLinks.id}
img= {socialLinks.img}
name= {socialLinks.name}
href= {socialLinks.href}
/>
)
}
function App() {
return (
<div>
<Header />
<Card {links.map(createCard)} />
</div>
);
}
export default App;
use the React map method
function App() {
return (
<div>
<Header />
{
links.map((link, linkKey) => (
<Card
key={linkKey}
img= {socialLinks.img}
name= {socialLinks.name}
href= {socialLinks.href}
/>
))
}
</div>
);
}
I am trying to render the TEXT CLOUD in my Nextjs app, but it is getting rendered infinite time.I am using Next JS. Please help
Here is the code and screenshots:
import dynamic from "next/dynamic";
import { useRef} from "react";
const container = '.tagcloud';
const texts = [
'3D', 'TagCloud', 'JavaScript',
'CSS3', 'Animation', 'Interactive',
'Mouse', 'Rolling', 'Sphere',
'6KB', 'v2.x',
];
const tag = {
radius: 100,
maxSpeed: 'normal',
initSpeed: 'fast',
direction: 135,
keep: true
}
const Text_cloud=dynamic(
() => {
const refTag=useRef();
return <span ref={refTag}>{TagCloud(container,texts,tag)}</span>;
},
{ ssr: false }
);
export default Text_cloud;
I am exporting this Component and using it in another page skills:
import React, { useState,useRef } from "react";
import Web from "../Component/web";
import Programming from "../Component/programming";
import Editing from "../Component/Editing";
import styles from "../styles/skill.module.css"
import Btn from "../Component/btn";
import Text_cloud from "../Component/text_cloud";
function Skill() {
const [skill, setskill] = useState("Web")
return (<>
<div className={styles.main}>
<ul className={styles.ruler}>
<a onClick={() => setskill("Web")} className={styles.skilla}><Btn name="Web Dev" /></a>
<a onClick={() => setskill("Programming")} className={styles.skilla}><Btn name="Programming" /></a>
<a onClick={() => setskill("Editing")} className={styles.skilla}><Btn name="Editing" /></a>
</ul>
<div className={styles.cld} >
<div className="tagcloud" >
<Text_cloud />
</div>
</div>
</div>
{skill === "Web" && <Web />}
{skill === "Programming" && <Programming />}
{skill === "Editing" && <Editing />}
</>)
}
export default Skill;
After running the server I get this output and error:
It get render two times
And the error it shows is:
Here is the error Screenshot
Please help me out here
I need your help. I try to insert in an array with objects of a photo, to erase and then to deduce. I have no errors in the code, but instead of a photo it shows me a photo icon. All my photos are in a separate folder inside the src folder. Tell me if I'm doing it right or how do I insert a photo into the object and then erase it? Thank you very much
Pizza.js
export let pizza_description = [
{ id: 1,
title: 'title 1',
image: 'bavarska.jpg'},
{ id: 2,
title: 'title: 2',
image: 'salami.jpg'}
]
Pizza_page
import React, {useState} from "react";
import {pizza_description} from "../Food_description/Pizza/Pizza";
export let Pizza_page = () => {
let [pizza, different_pizza] = useState(pizza_description)
return (<div>
{pizza.map(el => <div key={el.id}>
<img key={el.id} src={el.image}/>
<h1>{el.title}</h1>
</div>)}
</div>)
}
You have to import the images or put them in the public directory then reference them like
return (<div>
{pizza.map(el => <div key={el.id}>
// assuming that el.image = image name + extension
<img key={el.id} src={`/pizPhotos/${el.image}`}/>
<h1>{el.title}</h1>
</div>)
}
</div>)
}
I need to import images(several) from my image file dynamically by a map method. First, I want to set a base URL to my images file and then read the image's name from my JSON file which includes the image property and then set the image src accordingly.
The JSON file is like below :
{
"title": "Blue Stripe Stoneware Plate",
"brand": "Kiriko",
"price": 40,
"description": "Lorem ipsum dolor sit amet...",
"image": "blue-stripe-stoneware-plate.jpg"
},
{
"title": "Hand Painted Blue Flat Dish",
"brand": "Kiriko",
"price": 28,
"description": "Lorem ipsum dolor sit amet...",
"image": "hand-painted-blue-flat-dish.jpg"
},
my images folder :
I have read the products by redux which is works perfectly =>
const products = this.props.products;
console.log(products, 'from redux');
const fetchProducts = [];
for (let key in products) {
fetchProducts.push({
...products[key]
});
}
the console.log() =>
Now I want to define a base URL like this which later use as image src by adding the image's name from the JSON file in the map method :
const baseUrl = '../../components/assets/images/';
const fetchProducts = [];
for (let key in products) {
fetchProducts.push({
...products[key]
});
}
const productCategory = fetchProducts.map((product, index) => {
return (
<Photo
key={index}
title={product.title}
brand={product.brand}
description={product.description}
imageSource={baseUrl + product.image}
imageAlt={product.title}
/>
);
});
my Photo component looks like below :
const photo = props => (
<div className={classes.Column}>
<img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />
<div className={classes.Container}>
<p>{props.brand}</p>
<p>{props.title}</p>
<p>{props.price}</p>
</div>
</div>
);
export default photo;
unfortunately, I have faced this error:
Thanks in advance and sorry for my bad English :)
Import is not working like that. You can use a base URL like that:
const baseUrl = "../../components/assets/images/";
Then you can pass to your Photo component like that:
<Photo
key={index} // Don't use index as a key! Find some unique value.
title={product.title}
brand={product.brand}
description={product.description}
imageSource={baseUrl + product.image}
imageAlt={pro.title}
/>;
Lastly, in your Photo component use require:
<img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />
or like that:
<img src={require( "" + props.src )} alt={props.imageAlt} />
But, don't skip "" part or don't use it directly like:
<img width="100" alt="foo" src={require( props.src )} />
since require wants an absolute path string and first two do this trick.
Try this solution for dynamic image:-
**Componet**
const photo = props => (
<div className={classes.Column}>
<img src={require( `../../components/assets/images/${props.imageSource}`)} alt={props.imageAlt} />
<div className={classes.Container}>
<p>{props.brand}</p>
<p>{props.title}</p>
<p>{props.price}</p>
</div>
</div>
);
**Include Componet**
const productCategory = fetchProducts.map((product, index) => {
return (
<Photo
key={index}
title={product.title}
brand={product.brand}
description={product.description}
imageSource={product.image}
imageAlt={product.title}
/>
);
});
So here is what I found and it worked for me.
"file-loader": "4.3.0"
React: 16.12
Run this in your terminal:
npm run eject
Check file-loader in config/webpack.config and located file-loader configurations. What I did was, I created a directory called static/media/{your_image_name.ext} following the notation there:
options: {
name: "static/media/[name].[hash:8].[ext]"
}
and then imported this image like
import InstanceName from "static/media/my_logo.png";
Happy Hacking!
After trying all kinds of solutions, including backticks <img src={require( `${ props.imageSource }` )} and others, nothing was working. I kept getting the error Cannot find module, even though my relative paths were all correct. The only primitive solution I found, if you have a relatively small number of possible images, is to predefine a Map that will map to the actual imports. (Of course this won't work for lots of images.)
import laptopHouse from '../../images/icons/laptop-house.svg'
import contractSearch from '../../images/icons/file-contract-search.svg'
..
const [iconMap, setIconMap] = useState({
'laptopHouse': laptopHouse,
'contractSearch': contractSearch,
..
});
..
<img src={iconMap[props.icon]} />
i solved this typescript issue as follows in my project.
hope this is helpful
export const countryData = {
'sl': { name: 'Sri Lanka', flag: '/flag-of-Sri-Lanka.png' },
'uk': { name: 'UK', flag: '/flag-of-United-Kingdom.png' },
'usa': { name: 'USA', flag: '/flag-of-United-States-of-America.png' },
'ca': { name: 'Canada', flag: '/flag-of-Canada.png' },
'It': { name: 'Italy', flag: '/flag-of-Italy.png' },
'aus': { name: 'Australia', flag: '/flag-of-Australia.png' },
'me': { name: 'Middle East', flag: '/flag-of-Middle-East.png' },
'other': { name: 'Other', flag: '/flag-of-World.png' }, };
"part of URL within Double quotes" + dynamic_URL_via_var combo worked for me.
<Avatar src={require('../assets'+countryData['uk']['flag'])} />
//json data.
"ProductSlider":[
{
"image":"Product1.jpg"
},
{
"image":"Product2.jpg"
}]
//mapping data list in parent component.
{sliderData.map((data) => (
<SwiperSlide className='w-10 '>
<ProductCard data={{imgSrc: data.image}} />
</SwiperSlide>
))}
//child component(linked image).
import React from 'react'
import { CardImg } from 'react-bootstrap'
export default function ProductCard(props) {
let {imgSrc} = props.data;
return (
<div className="overflow-hidden">
<div className='overflow-hidden bg-grey opacity-card' >
<CardImg
variant='top'
src={require(`../assets/images/${imgSrc}`)}
/>
</div>
<div className='text-center p-1 opacity-card-title' >
<div>Add to cart</div>
</div>
</div>
)
}
Even I got the same error
{gallery.map((ch, index) => {....
cannot find module '/../..................png'
I went wrong here, I used src instead of ch
Error
<Image src={src.image} />
Solved
<Image src={ch.image} />