importing image dynamically (React Js) (Require img path cannot find module) - javascript

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} />

Related

Display image from another js file

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>
);
})}

How to declare file-path in Javascript for object mapping?

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.

Add photo in object and show it

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>)
}

Broken icon is displayed for the image with alt text

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>

How to use require() with variable names in react?

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;

Categories