Error using JSON object as property for Image source - javascript

so guys i have the path of images coming from a JSON File likes this
[
{
"name": "Cebola Roxa",
"price": 4,
"quantity": 0,
"path": "../assets/productsImages/purpleonion.png"
},
{
"name": "Cenoura",
"price": 4,
"quantity": 0,
"path": "../assets/productsImages/carrot.png"
},
]
The path for the images are correct, the problem is that when i try to use this path inside of o source using require it says Sintax Error
import products from '../assets/products.json'
const listProducts = products.map((product,index) => {
return( <Image source={require(product.path)} style={styles.imgProduct} />)
}
How can i load images using the path from a JSON file ?

Related

Get local img from js file

I am using this js file
export const sliderData = [
{
"id": 1,
"name": "Horse",
"brand": "Ferrrari",
"img": "https://www.formula1.com/content/dam/fom-website/manual/Misc/2022manual/WinterFebruary/RedBullRB18/SI202202090260_hires_jpeg_24bit_rgb.jpg.transform/9col/image.jpg"
},
{
"id": 2,
"name": "Power",
"brand": "Red Bull",
"img": './redbull.jpg'
},
{
"id": 3,
"name": "Arrow",
"brand": "Mercades",
"img": "src/images/merc.jpg"
}
]
And in my react, after mapping through them, I wanted to render them as {team.img} but only the first only is loading.
My folder structure is as follow:
src
|_data
| |_teams.js
|
|_images
| |_redbull.jpg
The only way to do this is to place each image in the public folder and use only paths inside of this folder.
create-react-app doesn't serve images from outside this folder.

Javascript/React code - control/page won't render in fileReader.onload

I have a react page and one of my inputs is a file upload. When loading, I want to read in the file (it's JSON) and then show the file as a tree to allow my users to select nodes (rules) to run against another dataset. BUT, when I pick the JSON file and the 'onload' event handler actually fires off, the page just stops rendering, I get a blank screen. I'm not sure why, I can't see any errors, but I AM IGNORANT with react and kinda new with javascript as well. So, this is quite likely just a dumb thing I'm doing. Can someone point me at what I'm doing wrong here?
handleRules(event) {
const ruleRdr = new FileReader();
ruleRdr.onload = async (e) => {
const rBuf = (e.target.result);
const rData = JSON.parse(new TextDecoder().decode(rBuf));
// the data is there, but it's not mapping into the tree...!?!?!?
const tree = {
name: "QA/QC Rules",
id: 1,
toggled: true,
children: rData.map((wFlow, index) => ({
name: wFlow.WorkflowName,
id: index,
children: wFlow.Rules.map((rule, idx) => ({
name: rule.RuleName,
id: idx
}))
}))
};
this.setState({ ruleData: rData, hasRules: true, treeData: tree });
}
ruleRdr.readAsArrayBuffer(event.target.files[0]);
}
EDIT #1: I don't think it's the code above now, I think it might be my tree library (react-treebeard) or my ignorance on how I'm using it. The code produces what I think is useable data, but it isn't rendering it out.
{
"name": "QA/QC Rules",
"id": 1,
"toggled": true,
"children": [
{
"name": "COMP",
"id": 0,
"children": [
{
"name": "ParentMustHaveCat",
"id": 0
},
{
"name": "ParentMustHaveMfg",
"id": 1
},
{
"name": "ParentMustHaveFamily",
"id": 2
},
{
"name": "SymbolsMustHaveFamily",
"id": 3
}
]
},
{
"name": "PNLCOMP",
"id": 1,
"children": [
{
"name": "ParentMustHaveCat",
"id": 0
},
{
"name": "ParentMustHaveMfg",
"id": 1
},
{
"name": "ParentMustHaveFamily",
"id": 2
},
{
"name": "SymbolsMustHaveFamily",
"id": 3
}
]
},
{
"name": "PNLTERM",
"id": 2,
"children": [
{
"name": "ParentMustHaveCat",
"id": 0
},
{
"name": "ParentMustHaveMfg",
"id": 1
},
{
"name": "ParentMustHaveFamily",
"id": 2
},
{
"name": "SymbolsMustHaveFamily",
"id": 3
}
]
}
]
}
I figured it out. I switched to MUI since it has more components that I will want to use anyway. I got a similar issue with it as well and realized that I have duplicate IDs between the parent and the children, and was creating a kind of lock when trying to compare parent and child IDs in the MUI library. Totally on me - I'm dumb.

React. Streaming JSON file

I don't have any backend logic and database. For data I just use a json file of humans.
Here it is:
[
{
"id": 0,
"name": "Andrew"
},
{
"id": 1,
"name": "Daniel"
},
{
"id": 2,
"name": "John"
},
{
"id": 3,
"name": "Frank"
}
]
Can I somehow stream this JSON file in React (i.e. on client side) to, for example, retrieve only the first two notes and return the array? I tried FS module but it only works for SSR. Or there's no way I can runtime stream it getting desired data? I just don't wanna return the whole array since I'm trying to imitate a backend database

How to add src path into vue component from json file

How to render images, if i get path from json file. Default i use require('../assets/img/item-image.png'). But i have no idea, how use it in this case
Component:
<div v-for="(item, index) in items">
<img :src="item.src">
</div>
<script>
import axios from 'axios'
export default {
name: 'componentName',
data () {
return {
items: null
}
},
mounted () {
axios
.get('./test.json')
.then(response => (this.items = response.data))
}
}
</script>
JSON file:
[
{
"id": 1,
"title": "item title",
"src": "../assets/img/item-image.png",
"alt": "item-image",
"text": "item body"
}
]
You need to keep using require() in order to let Webpack know to include your images when bundling.
Because Webpack bundles at compile time and your images are only known at runtime, this is best done by keeping part of the path static so Webpack can optimistically include the right files.
For example, if all your images are under ../assets/img, the best option would look like this
async mounted () {
const pathRegex = /^\.\.\/assets\/img\//
const { data } = await axios.get("./test.json")
this.items = data.map(item => ({
...item,
src: require(`../assets/img/${item.src.replace(pathRegex, "")}`)
}))
}
Webpack will then bundle every file under ../assets/img and at runtime, will be able to resolve the paths you supply.
See https://webpack.js.org/guides/dependency-management/#require-with-expression
You must add require
<img :src="require(item.src)">
This was how I solved it. I kept getting an error when using the regex above to add require to the src attribute in the json. This is what I did instead and it worked for me.
I am using fetch() to read the json which I am watching with json-server. The json is basically an array (cokeImages) of objects when you use res.json() to convert it.
{
"cokeImages": [
{
"title": "Cocacola Life",
"description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
"src": "../assets/cocacola-cans/cocacola-life.png",
"id": 1,
"name": "cocacola-life",
"nutrition": [
{ "title": "sodium", "value": "150 cl", "percent": "25%" },
{ "title": "Total Fats", "value": "0g", "percent" : "0%" },
{ "title": "sodium (mg)", "value": "40mg", "percent": "0%"},
{ "title": "potasium", "value": "4g", "percent": "0%" },
{ "title": "calcium", "value": "0g", "percent": "0%"}
]
},
{
"title": "Cocacola Zero",
"description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
"src": "../assets/cocacola-cans/cocacola-zero.png",
"id": 2,
"name": "cocacola-zero",
... (and so on)...
as you can see, the name property in each object is also the name I used in each images src.
It is that name property I used in the map() method to attach require to each src.
mounted(){
fetch("http://localhost:3000/cokeImages")
.then(response => response.json())
.then(arrayOfOjects => {
console.log(arrayOfObjects)
this.cokeImages = data.map(eachObject => {
return {...eachObject, src: require(`../assets/cocacola-cans/${eachObject.name}.png`)}
})
console.log(this.cokeImages)
})
.catch(err => {
console.log(err.message)
})
}

How to fetch data from json in Angular2 (TypeScript) without HTTP?

I have task (auth):
All data should be stored in LocalStorage.
Application should be written without back-end languages or services
You should create a json file with 10 test users and get it content while application forming.
Save user to LocalStorage.
I create a json file with data of users, but i don't understand how to fetch it in my service.
{
"Users": [
{
"Id": 1,
"name": "FirstUser",
"email": "1stemail#gmail.com",
"password": "test123"
},
{
"Id": 2,
"name": "2thUser",
"email": "2themail#gmail.com",
"password": "test123"
}
]
}
I tried some tricks like
"import as data from '../shared/users.json'
"const users = data.Users" (error on Users)
Do you have idea "how to" ?
I think it should be import * as data from '../shared/users.json but your system.config might add .ts or .js extension at the end of it.
The way I prefer to do it is to export it as a variable inside a ts file
export var data = {
"Users": [
{
"Id": 1,
"name": "FirstUser",
"email": "1stemail#gmail.com",
"password": "test123"
},
{
"Id": 2,
"name": "2thUser",
"email": "2themail#gmail.com",
"password": "test123"
}
]
}
then import that variable inside your component
import { data } from '../shared/users';
Full plunker example: http://plnkr.co/edit/CGtxYJkcjYt2cEzrbL00?p=info

Categories