Hi
I am currently trying to display elements of a list in react and I'm not able to load images using require.
I am using CRA and haven't changed webpack.config.js.
The list
import img1 from "../../assets/work-in-progress.png";
const projects = [
{
id: 1,
image_path: img1,
title: "t1",
category: "testing"
},
{
id: 2,
image_path: require("../../assets/work-in-progress.png"),
title: "t2",
category: "testing"
},
]
How I am displaying the images
<img src={ entry.image_path } alt="Project's" className="rounded" />
Currently, the first image is being displayed correctly but the second doesn't load.
I have already tried using src={ "" + entry.image_path } and got the same result.
I think your path isn't correct. It's working in my end. Here is the working code
Related
I have a little problem. I don't know how to pass this local images dynamicly.
Lets say I have API which returns static 6 store schema like that.
stores: [{id:1, name: "Wallmart"}, {id: 2, name: "Amazon"}];
and I have some images called store1.jpg, store2.jpg ...etc.
So I import images like that.
import store1 from "./store1.jpg"
So I need to loop these images dynamicly according to id.
{
stores.map((store) => (
<img src={`store${store.id}`} />
)
}
So, My question is what is best way to do that. maybe I can create some object which contains all images or import all images like that. I didn't check this version maybe it's not working at all. It doesn't looks like proper way. Can someone just advice me something who have experinced with that ?
Forget about importing the images, and just downright use the path to the images in the stores.map function.
<img src={"store" + store.id + ".jpg"} />
I found this type of solution because I figure out that I also have colors. I add all my images into public/images folder
export const stores : any = {
store1:{
id: 1,
src: "/images/store1.png",
tertiary: "#000",
primary: "#FFF",
},
store2:{
id: 2,
src: "/images/store2.png",
tertiary: "#999",
primary: "#aaa",
}
...
}
so I import stores and loop like that.
import {stores} from "./constants"
{
store.map((item:any) => (
<StoreCatalogCard
title={item.name}
img={stores[`store${item.id}`].src}
primaryColor={stores[`store${item.id}`].primary}
tertiaryColor={stores[`store${item.id}`].tertiary}
light={true}
/>
))
}
I am trying to dynamically render images from a local folder within my project
The object structure looks like this
{
id: 2,
text: 'How would you describe your level of influence in management of the farm?',
type: 'cardChoice',
choices: [
{
id: 1,
text: 'I am the primary decision maker',
questionId: 'Hm?',
value: 'I am the primary decision maker',
image: '1.jpg',
},
{
id: 2,
text: 'I hent',
questionId: 'Hrm?',
value: 'I',
image: '2.jpg',
},
{
id: 3,
text: 'I arm',
questionId: '?',
value: 'Irm',
image: '3.jpg',
},
],
},
In my component I select the folder that contains the images const baseUrl = '../../assets/images/CNA'
After that, in my return I try to render the images
<img src={`${baseUrl}'${questionChoice.image}'`} alt={questionChoice.text} />
The page renders, but my image isn't loading and it's showing my alt instead
Heres my full component
const CardChoiceQuestions = ({ cardChoiceArray, currentAnswer, updateCurrent, submitAnswer }) => {
const { id, value } = currentAnswer
const baseUrl = '../../assets/images/CNA'
return (
<ButtonContainer>
{cardChoiceArray.map(questionChoice => {
return (
<Button
active={questionChoice.id === id}
type="button"
key={questionChoice.id}
onClick={() => {
const answer = { id: questionChoice.id, value: questionChoice.value }
updateCurrent(answer)
submitAnswer()
}}
>
<p>{questionChoice.text}</p>
<img src={`${baseUrl}${questionChoice.image}`} alt={questionChoice.text} />
</Button>
)
})}
</ButtonContainer>
)
}
I don't have my laptop in front of me but a few things I noticed. Do you need a slash "/" after your base url? Also, the string concatenation should be completed in one set of brackets after the $ sign. Not sure if that's the issue try a few console.log(string path) amd verify it is going where you think it is. It looks like the path may be wrong. You may be better off conditional rendering images as opposed to building a dynamic url but either way it should render on change.
<img src={`${baseUrl}/${questionChoice.image}`} alt={questionChoice.text} />
use like this
Leaving this here in case someone comes across this...
<img src={require(`../../assets/images/CNA/${questionChoice.image}`)} alt={questionChoice.text} />
Not sure why I can't use ${baseUrl} but this works for now.
I am trying to give image name in src dynamically. I want to set image name dynamically using variable with path. but I am not able to set src correctly. I tried solutions on stackoverflow but nothing is working.
I tried to give path like this
<img src={`../img/${img.code}.jpg`}></img>
<img src={'../img/' + img.code + '.jpg'}></img>
<img src={'../img/{img.code}.jpg'}></img>
my images are saved in src/img path
if i give path like this
<img src={require('../img/nokia.jpg')}/>
image is showing
I know this question is asked before but nothing is working for me.
Please help me how can I set image path?
if you dont want to require the image then you have to put all your images into public folder and then
<img src={`../img/${img.code}.jpg`}></img>
this method will work.
You can still use require
<img src={require(`./img/${img.code}.jpg`)}/>
It's not recommended to manually add images to the public folder. See this answer here: https://stackoverflow.com/a/44158919/1275105
One pretty simple solution:
// images.js
const images = [
{ id: 1, src: './assets/image01.jpg', title: 'foo', description: 'bar' },
{ id: 2, src: './assets/image02.jpg', title: 'foo', description: 'bar' },
{ id: 3, src: './assets/image03.jpg', title: 'foo', description: 'bar' },
{ id: 4, src: './assets/image04.jpg', title: 'foo', description: 'bar' },
{ id: 5, src: './assets/image05.jpg', title: 'foo', description: 'bar' },
...etc
];
export default images;
You can then import it form another component like this:
// MyComponent.js
import images from './images'
//...snip
{ images.map(({id, src, title, description}) => <img key={id} src={src} title={title} alt={description} />)
Dynamic require doesn't seems to be clean and also eslint isn't happy with it (not sure why)
Other two approaches if images are stored in public folder :
const imgNameWithPath = '/fullImageNameWithPath.jpg'
Using env
<img src={process.env.PUBLIC_URL + imgNameWithPath} />
Using location origin:
<img src={window.location.origin + imgNameWithPath} />
If you guys get the path from the database for multiple images and need to use in single tag, you can follow the below method.
step 1 : Please make sure the images are in public folder.
step 2 : Update your path should start from public not from src.
step 3 : Make sure to verify that the path should be using like a variable. If your images path should be using in variable imgPath. You can use your code like var imgPath = '/img/pic.jpeg'
"src={imgPath}"
I hope this will help you..
I have an array of object like that :
{ id: 33617,
datePublication: 1532266465,
dateUpdate: 1532266574,
headline: 'An headline title here',
images: [ [Object] ] },
{ id: 33614,
datePublication: 1532265771,
dateUpdate: 1532271769,
headline: 'another super headline article',
images: [ [Object], [Object], [Object], [Object], [Object] ] }
so i iterate that way on my vue js template :
<v-flex v-for="(ip, i) in ips" :key="i" xs12 sm6 >
<v-card>
<v-card-media
:src="ip.images[0].url"
height="200px"
/>
<v-card-title primary-title>
<div>
<h3 class="headline mb-0">{{ ip.headline }}</h3>
<div>Located two hours south of Sydney in the <br>Southern Highlands of New South Wales, ...</div>
</div>
</v-card-title>
<v-card-actions>
<v-btn flat color="orange">Share</v-btn>
<v-btn flat color="orange">Explore</v-btn>
</v-card-actions>
</v-card>
</v-flex>
And here is my associated script :
var api = "https://my api.org/news/fr-FR/2018-25-07";
export default {
data() {
return {};
},
layout: "no-live",
async asyncData({ app }) {
const ips = await app.$axios.$get(api);
console.log(ips);
return { ips };
}
};
Each object in the images array should return me an id and an url, so i want to take that url as a source in my image but i have this error : Cannot read property '0' of undefined
it seems i need to do another loop over the images array, is there a proper way to do that with vue JS ?
if you have any objects in ips that doesn't have images, you would get that error,
you can try to add a conditional to not have an error in rendering
<v-card-media
v-if="ip.images && ip.images[0]"
:src="ip.images[0].url"
height="200px"
/>
I usually add a <pre>{{ip}}</pre> in these cases to see what's going on.
Try put v-if="ip.images" on v-card-media component. You will assure the images are not empty and loaded.
My app is created with create-react-app,
Im iterating with .map through my JSON file where I store the local path to the image but I assume create-react-app changes the pathing somehow and I don't understand how.
const list = this.state.people.map((d, i) => { return <li
key={i}
className="content"
style={{ backgroundImage: `url(${d.Picture})` }}
>
Above is my opening li tag where I loop out the data from my JSON file below:
The Picture in "Adam" works great and shows up on the page, however that is not where the picture is stored. I found that path in chrome dev tools so I just copy pasted.
The example below in "Bob" is the actual path to the img (from root)
I want to be able to put all my images in the images folder and store the correct path in the JSON file
{
"Name": "Adam",
"Born": 1971,
"Picture": "/static/media/elonmusk.3489bce1.jpg"
},
{
"Name": "Bob",
"Born": 1999,
"Picture": "/src/css/images/elonmusk.jpg"
},
Above is my folder structure, App.js is where i render the data, persons.json is where i store the file path, and images is the folder where I have the images
Images need to be statically analysable so you need to require them. Please refer to this for more background info.
So with your example above, instead of using a jsonfile create a people.js file instead like this with require statements for each image:
// file: people.js
const people = [
{
id: 0,
name: 'Adam',
born: 1971,
picture: require('../path/to/image.jpg')
},
{
id: 1,
name: 'Bob',
born: 1999,
picture: require('../path/to/image2.jpg')
}
]
Then you can map over this info to produce the jsx and your images will render.
const people = require('../path/to/people.js')
renderPeopleList () {
return people.map(p =>
<div key={p.id} style={{ backgroundImage: `url(${p.picture})` />
)
}