I have read many solutions on stack overflow and blogs but none could solve my problem.
I have image urls from api. It is uncommon but it is an assignment to me
productsdata= {
id: 12,
title: "Cat Tee Black T-Shirt",
description: "4 MSL",
availableSizes: ["S", "XS"],
style: "Black with custom print",
price: 10.9,
installments: 9,
currencyId: "USD",
currencyFormat: "$",
isFreeShipping: true,
src_1: "../../assets/113_1.jpg",
src_2: "../../assets/113_2.jpg"
},
here I am displaying image as
{productsdata.map(product => {
return (
<>
<img src={product.src_1} width="200" height="200" alt="tshirt" />
{/* <img src={product.src_2} width="200" height="200" /> */}
</>
);
})}
but it doesn't work as require() only works with static url.
Could someone pls help me?
I changed the image urls as
productsdata= {
src_1: "113_1.jpg",
src_2: "113_2.jpg"
},
and changed the 'src' attribute as
<img src={require(`../../assets/${product.src_1}`)} width="200" height="200" alt="tshirt" />
It worked fine. Here also 'require' is using variable and dynamic url. Who on the earth would think of writing this way. I think it's a bug in javascript or I don't have enough understanding:p
you should use like this-
import React, {useState} from 'react';
import Products from './old';
const New = (props) =>{
return(
<div>
{Products.map((Product, i)=>(
Object.values(Product).map((prod, i) => (
<div key={i}>
<p>id: {prod.id}</p>
<p>category: {prod.category}</p>
<p>filename: {prod.filename}</p>
<p>name: {prod.name}</p>
<p>price: {prod.price}</p>
</div>
))
)
)}
</div>
);
}
export default New;
Related
I am working on a personal react project for learning and considering to mapping data from a JavaScript object file (not JSON in this case). There are many ways to do it. This method of works for me
import product1 from "../../assets/images/products/product1.jpeg";
<img src={ product1 } alt="item_image" />
But I want to do it differently. I want retrieve data from a JavaScript object file (not JSON) using mapping. My data.js file contains data like this-
const data = [
{
id: 1,
title: "Meat",
price: €2.5,
category: "Grocery",
path: "../../assets/images/products/product1.jpeg",
},
{
id: 2,
title: "Milk",
price: €1.25,
category: "Drink",
path: "../../assets/images/products/product2.jpeg",
}
]
export function getData () {
return data;
}
and mapping data in this way
import { getData } from "./data";
function Product () {
const product = getData();
return (
<>
{
product.map((item) => (
<div>
<div>
<div>
<div>
<span> { item.title } </span>
</div>
<div>
<span> { item.price } </span>
</div>
</div>
<div>
<img src={ item.path } alt="item-img" />
</div>
<div>
<div>
<span> { item.category } </span>
</div>
</div>
</div>
</div>
))
}
</>
);
}
export default Product;
But I failed to get the image from this. After looking on internet, I tried to declare the path property using this method path: "file:///home/user/Documents/testapp/src/assets/images/products/product1.jpeg"
Unfortunately this method also failed to get the product image. I am expecting a better solution from the community. --Thanks.
The images are not showing on the webpage, and I have been unable to figure out the problem.
here's my code. I had even tried using images locally on my computer, still the same.
import MeetupList from "../components/layout/meetups/meetupList";
const DATA = [
{
id: 'm1',
title: 'This is a first meetup',
image: 'https://unsplash.com/photos/nSY9XBCk58Y',
address: 'Meetupstreet 5, 12345 Meetup City',
description:
'This is a first, amazing meetup which you definitely should not miss. It will be a lot of fun!',
},
{
id: 'm2',
title: 'This is a second meetup',
image: 'https://unsplash.com/photos/nSY9XBCk58Y',
address: 'Meetupstreet 5, 12345 Meetup City',
description:
'This is a first, amazing meetup which you definitely should not miss. It will be a lot of fun!',
},
];
function AllMeetUpsPage(){
return <section>
<h1>All Meetups</h1>
<MeetupList meetups={DUMMY_DATA}/>
</section>
}
export default AllMeetUpsPage
#MeetupList component
import classes from './meetupList.module.css'
function MeetUpList(props){
return <ul className={classes.list}>
{props.meetups.map(meetup =>
<meetupItem key={meetup.id} id={meetup.id}
image={meetup.image}
title={meetup.title}
address={meetup.address}
description={meetup.description} />)}
</ul>
}
export default MeetUpList
export const TEST = () => {
const ImageData = [
{
src: "img-path",
alt: "this is x",
},
{
src: "img-path",
alt: "this is x",
},
{
src: "img-path",
alt: "this is x",
},
{
src: "img-path",
alt: "this is x",
},
];
return (
<div>
{ImageData.map((properties) => (
<img {...properties} />
))}
</div>
);
};
This is one way. You probably can't do {...properties} when you include description etc.
const MeetupList=({meetups})=>{
return(
<>
{
meetups.map((item,index)=>{
const[id,title,image,address,description]=item;
<>
<p>{id}</p>
<p>{title}</p>
//local image
<img src={require("path")}/>
//http images
<img src={image}/>
<p>{address}</p>
<p>{description}</p>
</>
})
}
</>
)
}
In order to load local images to your React.js application, you need to add require parameter in media sections.
I have an image called image.jpg inside the src -> images -> image.jpg. I have some problem with my image on my React app. My code is running well but the image does not show up instead on saving and loading the application, the image is not displayed but broken icon is displayed with alt text. How is it possible to solve this problem?
What I have tried is:
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
term: "",
names: [
{ name: "Deepak", job_profile: "Quality Analyst", description: "He is Passionate in Tester" },
{ name: "Deepinder", job_profile: "iOS Developer", description: "He is a Dedicated iOS Developer" }
],
filteredData: [{}]
};
}
render() {
let terms = "";
if (this.state.term) {
terms = this.state.term.toLowerCase();
}
return (
<div className="App">
<label>Search Employee: </label>
<input
type="text"
value={this.state.term}
id="searchEmp"
placeholder="Enter Name"
onChange={(event) => {
if (event.target.value.indexOf(" ") > -1) {
alert("Please don\'t enter space.");
this.setState({ term: "" });
return;
}
this.setState({ term: event.target.value });
}}
/>
<br />
<br />
{this.state.names &&
this.state.names
.filter((x) => x.name.toLowerCase().startsWith(terms) || (x.description.toLowerCase().includes(terms)))
.map((item) => {
return (
<div className="data-body">
<div>Name : {item.name}</div>
<div>Job Profile : {item.job_profile}</div>
<div>Description : {item.description}</div>
<div><img src={require('../src/images/image.jpg')} alt="profile_picture" /></div>
<input type="button" id="button"
value="Delete" onClick={() => {
this.setState
({ names: this.state.names.filter
(i => i.name !== item.name) });
}}/>
<div>{<br></br>}</div>
</div>
);
})}
</div>
);
}
}
export default App;
I assume that you are using create-react-app to bundle your project. If that is the case, you just need to put all your images in the public folder and just mention the name in the src attribute.
You don't need the require function while mentioning the source of an image.
So, your code should look like this:
<img src="image.jpg" alt="profile_picture"/>
If you want the image to reside in some part of your source directory, you can import the image from there and use it in your code as follows:
import Image from '../images/image.jpg'
<img src={Image} alt="profile_picture"/>
Edit
Using ES5 syntax, you could do the following:
const Image = require("../images/image.jpg")
<img src={Image} alt="profile_picture"/>
i hope this helps you
<div>
<img src='../src/images/image.jpg' alt="profile_picture" />
</div>
I'm trying to create a page in my React Js project, with the content on the left side and content's image on the right side. So far, I was able to create a toggle function that changes text and image according to the selected title, so, for example, if a user clicks title 1, text1 & image1 will be displayed, and when the user clicks title2, text2 & image2 will be rendered and etc. The problem is that images don't load until a title was clicked, but I need to display img1 when page loads for the first time(and then img1 should change to img2 or img3, depending on the clicked title).
codesandbox
My code:
import React, { useState } from "react";
import "./styles.css";
const data = [
{
id: "1",
key: "1",
title: "Title1",
text: "Text1.",
img: "1.jpg"
},
{
id: "2",
key: "2",
title: "Title2",
text: "Text2.",
img: "2.jpg"
},
{
id: "3",
key: "3",
title: "Title3",
text: "Text3.",
img: "3.jpg"
},
{
id: "4",
key: "4",
title: "Title4",
text: "Text4",
img: "4.jpg"
}
];
export default function App() {
const [toggled, toggle] = useState("");
return (
<div className="App">
{data.map(({ title, text, key, img }) => {
return (
<>
<div className="main">
<div className="text">
<h1 onClick={() => toggle(key)}>{title} </h1>
{toggled === key ? (
<>
<p>{text}</p>
</>
) : null}
</div>
<div className="img">
{toggled === key ? (
<>
<img src={img} key={key} className="photo" />
</>
) : null}
</div>
</div>
</>
);
})}
</div>
);
}
This is how the page is displaying on load now
This is how I want the page to be on load(with img1 being displayed)
What I would love to do is when the page is loaded, it should display img1, but when the user clicks title2, img1 should change to img2, any suggestions will be greatly appreciated,
Thank you.
I did a bit of refactoring for you, try this: https://codesandbox.io/s/toggle-kc3q2
I set the initial state to be "1" and using toggle and setToggle as the state and state setter
I'm posting my solution here, in case anyone else stumbles upon a similar problem. I added the following lines of code to my project:
***const [visible, setVisible] = useState(true);***
<h1 onClick={() => {
setToggle(key);
***setVisible(false);***
}}>
<div className="img">
***{visible && key === "1" ? (
<img src={img}
key={key}
/>)
: null}***
</div>
codesandbox
In this case, when the page is loaded, it displays img1 and only titles(without their texts), and only when a user clicks any title, a text, and its image is displayed.
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} />