How to get local images dynamically from .json file in React-native - json

I have json file named "Bread.json" following is the content of the file.
How to use image name dynamically in <Image>
I'm trying following but getting error. I'm getting image name's array from json file into the Flatlist, so {item.img} = my image name from json file. But not working!
<Image source={require('../images/'+{item.img})} />
So, how can I use image name in source of the <Image>, Also I can not use require() function into my json file. Any help?
"bread.json"
[
{
"id": "1",
"img": "1.jpg",
"cat": "Breakfast",
"title": "Small Semolina Griddle Breads"
},
{
"id": "2",
"img": "2.jpg",
"cat": "Side",
"title": "Corn Bread"
},
{
"id": "3",
"img": "3.jpg",
"cat": "Appetizer",
"title": "Fresh Tomato Bruschetta"
}
]

You can try this!
<Image source={getImageSource(item.img)} />
function getImageSource(image) {
let imageSrc = require('../images/logo.png');
switch (image) {
case "1.jpg":
imageSrc = require('../images/1.jpg');
break;
default:
break;
}
return imageSrc;
}

Hope this helps!
1) Create a file (to hold JSON data) e.g bread.js:
const Breads=[
{
"id": "1",
"img" : require('../images/1.jpg'),
"cat": "Breakfast",
"title": "Small Semolina Griddle Breads"
},
{
"id": "2",
"img" : require('../images/2.jpg'),
"cat": "Side",
"title": "Corn Bread"
},
{
"id": "3",
"img" : require('../images/3.jpg'),
"cat": "Appetizer",
"title": "Fresh Tomato Bruschetta"
}
]
export default Breads;
2) Then import the data in component and loop through the list using a FlatList
import Breads from './bread.js';
<FlatList
data={Breads}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => <View>
<Image source={item.src} />
<Text>{item.title}</Text>
</View>
}
/>

Related

issues with fetching Json in react

I apologise as this is probably either very basic or i've done something compeltely wrong. I'm brand new to React, and coding in general, and I'm trying to make a React app that shows the recipes im using on cards. The cards in turn should be searchable and dynamic, dissapearing if they don't match etc.
This is my app.js file, that when run, it just brings up my custom "Loading" screen without data. Where have I messed up on this?
import React, {Component} from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import Scroll from "./Scroll";
import "./App.css"
class App extends Component {
constructor() {
super()
this.state = {
recipes: [],
searchfield: "",
}
}
componentDidMount() {
fetch("./recipedata.json")
.then(response => { return response.json();})
.then(recipedata => {this.setState({recipes: recipedata})});
}
onSearchChange= (event) =>{
this.setState({searchfield: event.target.value})
}
render() {
const filteredRecipe = this.state.recipes.filter(recipes =>{
return recipes.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
if (this.state.recipes.length === 0) {
return <h1 class="f1 tc">Loading</h1>
} else {
return(
<div className="tc">
<h1 className="f1">Recipes</h1>
<SearchBox searchChange={this.onSearchChange} />
<Scroll>
<CardList recipe={filteredRecipe}/>
</Scroll>
</div>
)
}
}
}
export default App
Thanks in advance
edit: I have been asked to post the contents of recipedata.json:
[
{
"id" : 1,
"name" : "Carrot cake",
"type" : "sweet",
"author" : "Grandma",
"link" : "recipes/carrotcake.html"
},
{
"id" : 2,
"name" : "Spicy chicken pitta filling",
"type" : "savoury",
"author" : "Grandma",
"link" : "recipes/chickenpitta.html"
},
{
"id" : 3,
"name" : "Mushroom ham and chicken crusty puff pies",
"type" : "savoury",
"author" : "Grandma",
"link" : "recipes/crustypuff.html"
},
{
"id" : 4,
"name" : "Sweet potato pumpkin seed rolls",
"type" : "savoury",
"author" : "Grandma",
"link" : "recipes/sweetpotrolls.html"
},
{
"id": 5,
"name": "Wild mushroom wafer",
"type": "savoury",
"author" : "Grandma",
"link": "recipes/mushroomwafer.html"
},
{
"id": 6,
"name": "Piri Piri chicken sauce",
"type": "savoury",
"author": "Grandma",
"link": "recipes/piriRecipe.html"
},
{
"id": 7,
"name": "Chicken Liver Pate'",
"type": "savoury",
"author": "Grandma",
"link": "recipes/pate.html"
},
{
"id": 8,
"name": "Creamy mushroom pasta",
"type": "savoury",
"author": "Grandma",
"link": "recipes/mushroompasta.html"
},
{
"id": 9,
"name": "Cheesey garlic bread",
"type": "savoury",
"author": "Grandma",
"link": "recipes/gbread.html"
},
{
"id": 10,
"name": "Mini quiches",
"type": "savoury",
"author": "Grandma",
"link": "recipes/miniquiche.html"
},
{
"id": 11,
"name": "Sticky lemon ginger cake",
"type": "sweet",
"author": "Grandma",
"link": "recipes/stickyrecipe.html"
},
{
"id": 12,
"name": "Sticky toffee pudding",
"type": "sweet",
"author": "Grandma",
"link": "recipes/stickytoffee.html"
},
{
"id": 12,
"name": "Iced cream buns",
"type": "sweet",
"author": "Grandma",
"link": "recipes/icedcreambuns.html"
},
{
"id": 13,
"name": "Pineapple Cake",
"type": "sweet",
"author": "Grandma",
"link": "recipes/pineapplecake.html"
}
]
Edit 2:
Thanks for your help all, I've now fixed the app.js file and the Json is being returned. I'm now faced with this error in my CardList.js component:
TypeError: Cannot read property 'map' of undefined
CardList
C:/Users/mattj/OneDrive/Desktop/coding/gmcb-react-app/src/CardList.js:5
2 | import Card from './Card.js';
3 |
4 | const CardList = ({recipes}) => {
> 5 | return <div>
6 | {recipes.map((recipedata, i) => {
7 | return(
8 | <Card
code:
import React from 'react';
import Card from './Card.js';
const CardList = ({recipes}) => {
return <div>
{recipes.map((recipedata, i) => {
return(
<Card
key={i}
id={recipes[i].id}
name={recipes[i].name} />
)
})}
</div>
}
export default CardList
What have I messed up here?
Regarding issue #2 you posted it is really tough to say, however I think you are overcomplicating things with your card list. You should simply pass an array of filtered recipes to your component.
Your card list component you should just pass an entire recipe option to the component instead of trying to pass specific props. If in the future you add more keys to each recipe object you wont have to adjust your card list
const CardList = ({recipes}) => {
return (
<div>
{
recipes.map(recipe => {
return <Card recipe={recipe} key={recipe.id} />
})
}
</div>
)
}
Inside your card component you can destructure the keys off the recipe object
const Card = ({recipe}) => {
return (
<div>
<h3>{recipe.name}</h3>
<p>{recipe.type} - {recipe.author}</p>
<hr />
</div>
)
}
I made you a code sandbox, I used React Hooks and a mockAxios call in order to fake what a server would do and so you have some code for if you want to call an API in the future.
https://codesandbox.io/s/broken-glitter-4wb61?file=/src/App.js
You don't need to use fetch to get the data from the local json file.
You can simply import the contents of ./recipedata.json by doing this:
import recipedata from './recipedata.json';
And then change your componentDidMount to this:
componentDidMount() {
this.setState({ recipes: recipedata });
}
You mostly use fetch when you are trying to fetch data from a http server. Read more here and here
To support #Qubaish Bhatti's comment, yes, there is no need to have recipes in state. You can use it directly and do away with this.state.recipes

Vue.js Filtered list Method

I am still learning Vue.js. At the moment I am trying to make a simple filtered list method that pulls the data from a json file in Vue. I think that I am having trouble figuring out the correct syntax.
I just cant seem to get it right. Any help is more than welcome :)
This is Vue file:
<template>
<section>
<ul>
<li v-for="product in rings" :key="product">
{{product.title}}
</li>
</ul>
</section>
</template>
<script>
import data from '#/assets/data.json';
export default {
data() {
return {
products: []
}
},
methods: {
computed: {
rings(){
return this.products.filter(product => product.type == 'Ring')
}
}
}
}
</script>
And this is the Json file:
{ "products": [
{
"title": "Ring 1",
"description": "something",
"type": "Ring",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Halskæde 1",
"description": "something",
"type": "Halskæde",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Armbånd 1",
"description": "something",
"type": "Armbånd",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Ørering 1",
"description": "something",
"type": "Ørering",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
}
]
}
You imported the data but never used anywhere inside the component:
import data from '#/assets/data.json';
// notice the data here is just a variable and it has nothing to do with the
// component's data property
export default {
data () {
return {
products: data.products // init products with imported data
}
},
Or with the destructuring syntax:
import { products } from '#/assets/data.json';
export default {
data () {
return {
products // init products with imported data
}
},

react native json image

I want to print out JSON images as a variable.
This is my local JSON file (JsonData.json):
{
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": [ "1", "2" ],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2",
"name": "soup",
"condition": [ "2", "3" ],
"image": "./appetizer/soup.png"
},
…
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": [ "1" ],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": [ "2", "3" ],
"image": "./main/fish.png"
},
…
]
}
I filtered the name when condition="2". (salad,soup,fish)
This is the code for filtering name:
const newArray1 = [...JsonData["apptizer"], ...JsonData["main"]];
const JsonResult = newArray1.filter(item => {
if(item.condition.indexOf("2") !== -1) return item.name;
});
AND I want to get the image when condition="2".
How can I get them? And How can I print out them?
Do I have to use base64? If so, Can you tell me how to use it?
I saw the explanation, but I can't understand it.
And I imported JSON file this way (I've been correctly using it):
var JsonData = require('./JsonData.json');
You can use below code:
let mainObject = JSON.parse(JSON.stringify(data))
let allKeys = Object.keys(mainObject)
let finalObject = []
allKeys.map((value, index) => {
let array = mainObject[value]
array.map((aryObject, aryIndex) => {
let condition = aryObject['condition']
if (condition.includes('2')) {
finalObject.push(aryObject)
}
})
})
alert(JSON.stringify(finalObject))
You can import data in top of screen:
import { data } from './data';
You can add below text in data.js:
export const data = {
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": ["1"],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2222",
"name": "soup",
"condition": ["2", "3"],
"image": "./appetizer/soup.png"
},
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": ["1"],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": ["21", "3"],
"image": "./main/fish.png"
},
]
}
You can use Object#values to get the arrays corresponding to appetizer and main and then Array#flat to extract the nested objects into a transformed array. Then use the Array#filter (which you are already using) to filter out only the required objects based on your condition and then Array#map to get the name and image values out of every filtered object into an array of objects.
Please consider following snippts
const jsonData = {"appetizer":[{"num":"appetizer1","name":"salad","condition":["1","2"],"image":"./appetizer/salad.png"},{"num":"appetizer2","name":"soup","condition":["2","3"],"image":"./appetizer/soup.png"}],"main":[{"num":"main1","name":"beef","condition":["1"],"image":"./main/beef.png"},{"num":"main2","name":"fish","condition":["2","3"],"image":"./main/fish.png"}]};
const filteredValues = Object.values(jsonData)
.flat()
.filter(o => o.condition.includes('2'))
.map(({name, image}) => ({ name, image }));
console.log(filteredValues);
The output of the above code will be an array of objects having the following structure
[{
"name": SOME_NAME,
"image": SOME_PATH
},
{
"name": SOME_NAME,
"image": SOME_PATH
},
...
]
You can use the above array to retrieve your image path and display it accordingly.
I think you shouldn't be worried about base64 as images are stored locally and path will be sufficient to display the image.
Hope this will help!!!
Side Note: You can avoid the Array#flat part as you are already doing it manually [...JsonData["apptizer"], ...JsonData["main"]] but flat will be handy in case there are more keys in jsonData that need to be considered.

unable to call json nested object image properties

in my case i am unable to call properties from a nested image object properties.below is my code. I have to print price and image title on html page. I really dont knw where i am wrong. Any help will be helpful.
how i called data :
const singerDetails = JSON.parse(xhr.responseText);
for (let i = 0; i < singerDetails.abc.length;enter code here i++) {
console.log(singerDetails.abc[i].price);
}
but what should i do for image object ? i tried
console.log(singerDetails.abc[i].image.title); but it gives error ..
Json File :
{
"abc": [
{
"price": 9,
"tea": "black",
},
{
"image": {
"alt": "hi i m alt",
"title": "i am tittle",
},
"price": 10,
"tea": "green",
},
{
"price": 19,
"tea": "black",
},
{
"image": {
"alt": "hi i m alt2",
"title": "i am tittle2",
},
"price": 10,
"tea": "green",
}
]
}
delete last comma in each of obj properties/
JS Bin code here
{"price": 19,"tea": "black"}
...

Problems during getting data from external JSON in D3.js

I'm trying to load some data from the external JSON file to put them into the tooltip, but something is going wrong and I can't figure it out. My JSON looks like this:
{
"results": [
{
"name": "First Candidate",
"result": 52,
"victory": "winner",
"region": "First region",
"constituencyName": "First constituency",
"constituencyNumber": 1,
"partyName": "Ruling party",
"partyShort": "PR",
"partyStatus": "Right"
},
{
"name": "Second Candidate",
"result": 48,
"victory": "looser",
"region": "First region",
"constituencyName": "First constituency",
"constituencyNumber": 1,
"partyName": "Opposition party",
"partyShort": "OP",
"partyStatus": "Left"
}
]
}
It's the part of my code where I'm trying to get the data:
d3.json("test_json.json", function(error, data) {
dataViz(data.results);
});
Here is the full code on jsfiddle: http://jsfiddle.net/anton9ov/v1rz2vfu/
Use the full address for the json : http://jsfiddle.net/thatOneGuy/v1rz2vfu/15/
d3.json("https://dl.dropboxusercontent.com/u/23920803/infographics/2016/2016.08.29_elections_results/my_files/test_json/test_json.json", function(error, data) {
dataViz(data.results);
});