React backgroundImage referenced in JSON file path seem weird - reactjs

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

Related

How to display images from json URL when the images key has two object values

This is my first stackoverflow post....be kind
I am building a react app where I want to display an image from a array of objects but the "images:" object has two objects inside example:
[
{ value: "all", label: "All sets" },
{
value: "base1",
label: "Base",
series: "Base",
printedTotal: 102,
total: 102,
legalities: { unlimited: "Legal" },
ptcgoCode: "BS",
releaseDate: "1999/01/09",
updatedAt: "2020/08/14 09:35:00",
images: {
symbol: "https://images.pokemontcg.io/base1/symbol.png",
logo: "https://images.pokemontcg.io/base1/logo.png",
},
},]
my question is how would I access the inner object to display just the "logo:" object?
my assumption is to use a combination of .map and Object.keys() but I'm unsure how to do it.
mycode is below...
import React from "react";
import setOptions from "../data/sets";
export default function SetOverview() {
const sets = setOptions;
return (
<div>
{sets.map((set) => {
return (
<div key={set.value}>
<h2>{set.label}</h2>;<p>Number of cards: {set.printedTotal}</p>
<p>Release date: {set.releaseDate}</p>
</div>
// image to be placed here
);
})}
</div>
);```
ma friend. Welcome to Stack Overflow, and no- you will not be treated with kindness. That being said,
If you are sure about the keys that are being passed in the dataset, i.e.: objName.objItem.images.logo, then all you need to do is,
Check if the images key exists in that object (because your first object doesn't have it, so I suspect there may be a reason for that).
Load the image's logo value inside that div you've specified.
To achieve this, all you need to do is:
set.images?.logo && <img src={set.images.logo} />
And voila, you shall have your image. The question mark checks if key exists.

How to map through a json object that is stored in a react component not coming from an api?

I have a file inside my react project, glossaryItems.json. The file looks like this:
{
"glossary": [
{
"name": "Constant",
"pageNumber": "33",
"definition": "A value that cannot change while the program is running.",
},
{
"name": "Debugging",
"pageNumber": "45",
"definition": "The process of finding and reducing the number of defects in a computer program.",
},
{
"name": "Algorithm",
"pageNumber": "4",
"definition": "A strictly defined finite sequence of well-defined statements that provides the solution to a problem."
}
]
}
I have another file, glossaryPage.tsx where I would like to display each glossary item within a tab. I am not sure how to access the json file in order to use it within the tsx file. I ended up changing the json file to a .ts file and exported it as so:
export const glossaryItems =
[
{
"glossary": [
{
"name": "Constant",
"pageNumber": "33",
"definition": "A value that cannot change while the program is running.",
},
{
"name": "Debugging",
"pageNumber": "45",
"definition": "The process of finding and reducing the number of defects in a computer program.",
},
{
"name": "Algorithm",
"pageNumber": "4",
"definition": "A strictly defined finite sequence of well-defined statements that provides the solution to a problem."
}
]
}
]
And then imported it inside glossaryPage.tsx. I want to be able to get the each part of the json separately to be able to use it inside the tabs. So I would have one tab labeled "Constant", a second tab, "Debugging", a third tab "Algorithm" and under each tab display that information such as pagenumber and definition that applies to that tab. I tried mapping over just the glossary but was unable to. I had to map over the glossaryItems.
const GlossaryPage = () => {
const terms = glossaryItems.map(({glossary}, key) => (
<div key={key}>
{glossary.map(({name, pageNumber, definition}, key) => (
<div key={key}>
<p>{name}</p>
</div>
))}
</div>
))
return (
<SprkTabsPanel
isDefaultActive
tabBtnChildren={terms[0]} //this is where the terms are printing out on the tab
tabBtnAnalyticsString="tab-1"
tabBtnDataId="tab-1"
>
</SprkTabsPanel>
I thought that by indexing the terms it would give me the term at that index but it gives me all of the terms. This is what it looks like:
How can I get the individual values of the object?
Any help would be greatly appreciated!
Importing JSON
In order to import a .json file, you simply need to enable support in your tsconfig.json file. Set "resolveJsonModule": true inside the compilerOptions property. Now you can import the data from the JSON file as a default import.
Docs: Resolve JSON Module
Mapping Your Object
I had a look at the documentation for the Spark Design system and it seems like you need to create a separate SprkTabsPanel component for each tab. All of the individual tab panels go inside of one SprkTabs component.
import React from "react";
import { SprkTabs, SprkTabsPanel } from "#sparkdesignsystem/spark-react";
import glossaryItems from "./glossaryItems.json";
const GlossaryPage = () => {
return (
<SprkTabs idString="glossary-tabs">
{glossaryItems.glossary.map(({ name, pageNumber, definition }, key) => (
<SprkTabsPanel tabBtnChildren={name} key={key}>
<p>{definition}</p>
<p>Page Number: {pageNumber}</p>
</SprkTabsPanel>
))}
</SprkTabs>
);
};
export default GlossaryPage;

Requires not loading images in CRA

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

How to access a local image using a local image url in a json file in react native?

I have problem in accessing the local image url in a json file. The images are stored in image directory. I have got some image addresses stored in a JSON array like this :
jsonResponse=
[ {"id": "1", "myImage": "./image/img1.png", "myText": "Anytext"},
…
]
const first = jsonResponse[0]
But when I try calling that using first.myImage in Image, it doesn't work; I'm able to get everything else. So, I try calling it like:
source={require('{first.myImage}')} as well as source={require({first.myImage})}
But it says, invalid prop type. I am able to access all other elements. I have also updated the JSON as:
[ {"id": "1", "myImage": "require('./image/img1.png')", "myText": "Anytext"},
…
]
source={first.myImage} OR source={{first.myImage}}
but that gives the same error too. Please help me.
makesure you are accessing the image in the same directory where image resides or else navigate to the image with proper path
I'm assuming you are able to retrieve the filepath from the json file and that the path is correct. Based on that, try using:
jsonResponse = [{"id": "1", "myImage": "./image/img1.png", "myText": "Anytext"}, ...]
Then on your app create two const to hold your variables. The first one you'll use to save the path you retrieve from the json. The second will be the one you'll use as source of your Image component.
constructor() {
const imagePath = first.myImage;
const image = require(imagePath);
}
...
<Image
source={image}
style={{ height: 30, width: 30, resizeMode: 'contain' }}
/>
...
Alternatively, you can also try importing the image this way:
import image from first.myImage;
JSON File:
{
"id": 2,
"name": "Toyota Corolla XLI\\Hatchback Automatic",
"details": "4 seater, diesel",
"picture": "./static/images/XLI.jpg",
"overcharge": "PKR 179 per excess km",
"weekday": "PKR 190/hr",
"weekend": "PKR 287/hr"
},
And then add inyour .js file like this:
{PostData.map((postDetail, index) => {
return (
<Link href="details">
<Card className="carditem">
<Card.Body style={{ cursor: "pointer" }}>
<Row>
<Col xs="12" sm="4">
<img
src={postDetail.picture}
class="d-block"
height="170"
/>

How to give Image src dynamically in react js?

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..

Resources