ReactJS Display API in Component - json

I am new to react. I am using an api in the form of
{
"category": "dogs",
"available": [
{
"name": "pedro",
"breed": "chihuahua"
},
{
"name": "roxane"
"breed": "beagle"
}
]
},
{
"category": "cat",
"available": [
{
"name": "garfield",
"breed": "tobby"
}
]
}
I want to display ALL the pets available from the same category in name-breed pairs.
Example: Display all dogs
Pedro
Chihuahua
Roxane
Beagle
but that array is giving me hard times.
Attempt
App.jsx
{this.state.data.map((availablePets, i) => <Content key = {i} data = {Content} />)}
Content.jsx
{this.props.data.available[WhatDoIPutHere?].name}
{this.props.data.available[ajsnxnnx].breed}
Is there another way to display ALL the available pets from the same category in name-breed pairs?
SOLVED
{this.props.data.faqs.map((QA,i) =>
<div key={i}>
<h4>{this.props.data.category[i].name}</h4>
<p>{this.props.data.category[i].breed}</p>
</div>
)}

Your solution is not dynamic.
This will be a better solution.
{
this.props.data.faqs.map((QA,i) => {
const pets = QA.available.map((pets, j) => {
return <div key={j}
<h4>{pets.breed}</h4>
<p>{pets.name}</p>
</div>
})
return <div key={i}>
<h4>{QA.category}</h4>
{pets}
</div>
})
}

Related

React : filter json object with array of multiple possible values

I have a json object
I imported it in the react component like this
import data from "../data/data.json";
This is my json object
{
"Cocktail": [
{
"id": 1,
"name": "PL",
"illustration": "img1",
"ingredient": [{"percent": "1/10","ingredientname": "br"},
{"percent": "4/10","ingredientname": "or"},
{"percent": "5/10","ingredientname": "vo"}]
},
...
{
"id": 3,
"name": "AN",
"illustration": "img3",
"ingredient": [{"percent": "2/10","ingredientname": "br"},
{"percent": "2/10","ingredientname": "li"},
{"percent": "6/10","ingredientname": "ri"}
]
}
]
}
I have this array
ingred = ["br", "or"]
I want to filter the json object file :
ingredientsname which have one of the corresponding value of ingred array and return the name of each element associated
I tried this
return (
<>
{
data.Cocktail
.map((cocktail) => {
return (
<>
{
cocktail.ingredient.filter(ingredientcocktail => ingredientcocktail.ingredientname === ingred).map((ingredientcocktail) => {
return (
<span key={cocktail.name}>
</span>
);
})
}
</>
);
})
}
</>
);
But it doesn't work : I don't know how to pass through items of the second array for the filtering.
Can someone could help me ?
I think I found a solution :
data.Cocktails
.map((cocktail) => {
return (
<>
{
cocktail.ingredient
.filter(ingredientcocktail => ingred .includes(ingredientcocktail.ingredientname))
.map((ingredientcocktail) => {
return (
<div key={ingredientcocktail.ingredientname}>
{cocktail.name}
</div>
);
})
}
</>
);
})
}
Thank you for your answers.
Sorry, can't help you with ReactJs, but this should work in "plain" JS:
let obj = {
"Cocktail": [
{
"id": 1,
"name": "PL",
"illustration": "img1",
"ingredient": [{"percent": "1/10","ingredientname": "br"},
{"percent": "4/10","ingredientname": "or"},
{"percent": "5/10","ingredientname": "vo"}]
},
{
"id": 3,
"name": "AN",
"illustration": "img3",
"ingredient": [{"percent": "2/10","ingredientname": "br"},
{"percent": "2/10","ingredientname": "li"},
{"percent": "6/10","ingredientname": "ri"}
]
},
{
"id": 4,
"name": "asdasd",
"illustration": "asdasd",
"ingredient": [{"percent": "2/10","ingredientname": "asdasd"},
{"percent": "2/10","ingredientname": "asdasd"},
{"percent": "6/10","ingredientname": "asdasd"}
]
}
]
};
let wanted = ["br", "or"]
let res = obj.Cocktail.filter(
el => el.ingredient.some(
i => wanted.some(w => w == i.ingredientname)
)
).map(cocktail => cocktail.name);
console.log(res)
(This is not meant to be "the most efficient way", so please, if you have more efficient way to do it, feel free to make an answer, and not complain about it on the comments)

How to render a complex JSON array of array in React

I am new to React JS, I want to render this JSON containing Category and list of items below that category. Consider state.miData has this array response from server. It has category and list of menu items under that category. I want to show it in UI like Category and under that category list of items those fall in that category.
[
{
"category": {
"name": "Pasta",
"id": "P1"
},
"items": [
{
"menuItemId": "1",
"menuItemName": "Alfredo-Pasta"
},
{
"menuItemId": "2",
"menuItemName": "Macroni-Pasta"
}
]
},
{
"category": {
"name": "Burger",
"id": "B1"
},
"items": [
{
"menuItemId": "2",
"menuItemName": "UB-Burger"
},
{
"menuItemId": "1",
"menuItemName": "Thela-Mela-Burger"
}
]
}
]
I have written this code in render function but its not working.
const data = this.state.miData
const listItems = data.map((d) =>
<div>
<p key={d.category.id}>{d.category.name}</p>
<ul>
d.items.map((mi) =>
<li>{mi.menuItemName}</li>
);
</ul>
</div>
);
return (
<div>
{listItems}
</div>
);
Thanks in advance.
Try wrapping up the map for the list item in the curly braces.
<ul>
{
d.items.map((mi) =>
<li>{mi.menuItemName}</li>
);
}
</ul>

Getting the name of many properties inside a json file with reactjs

I have a functional component that looks like this:
import React from 'react'
import PropTypes from 'prop-types'
import Styles from './searchbar.scss'
const AutoFill = (props) => {
const results = props.results || {}
return (
<ul className={Styles.searchUl}>
{Object.entries(results).map(([key, value]) => {
console.log('VALUE', value)
console.log('VALUENAME', value.apple.name)
return (
<li className={Styles.searchLi}>
<a className={Styles.searchA} href={value.apple.href} target='_blank' rel='noopener noreferrer' key={value.href}>
{value.apple.name}
</a>
</li>
)
})}
</ul>
)
}
AutoFill.propTypes = {
results: PropTypes.array
}
export default AutoFill
I also have a Json file that looks like this:
{
"results": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
"box": {
"name": "box",
"href": "https://www.box.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
With console.log('Resultsssssss', (results[key].apple.name)) i get the specified name of apple only which returns obv apple.
So i want to know how i can return the name of all the objects at once, To show them in a UL under a searchbar for a autoFill when typed a everything of a should appear as suggestions: https://gyazo.com/006e856190e8e063934a07eb0725926e
Any answer will be highly appreciated and looked into.
First, you want to get all the values of the object. Object.values(results) will return an array that looks like this:
[
{
"name": "apple",
"href": "https://www.apple.com/"
},
{
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
{
"name": "box",
"href": "https://www.box.com/"
},
{
"name": "berserk",
"href": "https://www.berserk.com/"
}
]
Now you can use map to get the names: Object.values(results).map(x => x.name). This will return an array of names: ['apple', 'armadillo', ...].
When you passed 2 arguments in your map function, first one is general key of your json file, results in your case and second argument is content under this key.
Try this:
const AutoFill = (props) => {
const results = props.results || []
return (
Object.entries(results).map(([name, content]) => {
for (const key in content) {
if (content.hasOwnProperty(key)) {
console.log('Resultsssssss', (content[key].name))
}
}
})
)
}
You can simply return all properties within from within the map function without the for loop which you have in your code
const data = {
"results": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
"box": {
"name": "box",
"href": "https://www.box.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
const res = Object.entries(data.results).map(([key, value]) => {
return value.name;
});
console.log(res);
What you need for render is to restructure your HTML a little bit
const data = {
"results": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
"box": {
"name": "box",
"href": "https://www.box.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
const Styles = {}
const AutoFill = (props) => {
const results = props.results || {}
return (
<ul className={Styles.searchUl}>
{Object.entries(results).map(([key, value]) => {
return (
<li className={Styles.searchLi}>
<a className={Styles.searchA} href={value.href} target='_blank' rel='noopener noreferrer' key={value.href}>
{value.name}
</a>
</li>
)
})}
</ul>
)
}
ReactDOM.render(<AutoFill results={data.results} />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />

Converting html elements in json without using react packages and dangerouslysetinnerhtml

I have a json object which contains html tags in it.I have understood the disadvantage of using dangerouslySetInnerHTML and trying to use parse/stringify instead of it.But I could't convert the object to html tags.I'm not allowed to use any other react packages. So, is there any solution ?
[
{
"category": "Chapter",
"results": [
{
"content": "that <em>cultural</em> tool you don’t do a good job of it. From this perspective, <em>culture</em>",
"id": "4c00-b7f6-d6e0e252ae9e"
},
{
"content": "sample <em>culture</em>",
"id": "4c00-b7f6-d6e0e252ae9e"
}
]
},
{
"category": "Learning Objectives",
"results": [
{
"content": " <em>culture</em> is a communication.",
"id": "4c00-b7f6-d6e0e252ae9e"
},
{
"content": "sample <em>culture</em> which",
"id": "4c00-b7f6-d6e0e252ae9e"
}
]
}
]
import React from 'react';
import PropTypes from 'prop-types';
const Result = ({ data, onSearchResultClick }) => (<div >
{
data.map((category, index) => (
<div key={index}>
<div key={index}>{category.category}</div>
<hr />
<div className="searchShowData" >
{
category.results.map((result, resultIndex) => (
<p
key={resultIndex}
dangerouslySetInnerHTML={{ __html: (result.content) }}
onClick={() => onResultClick(result.id, result.type)}
/>
))
}
</div>
</div>
))
}
</div>);
Result.propTypes = {
data: PropTypes.array.isRequired,
onSearchResultClick: PropTypes.func.isRequired
};
export default Result;

Mapping object to child component in React

Using React I am trying to pass down a parsed JSON file and map through the object. However seeing as it is an object I can only map the object using Object.keys as below:
const question = Object.keys(questions).map((data, index) =>
<QuestionList questions={data} key={index} />
However using this I am only able to access the top level of my data structure. So using this code and passing down my object. Using Object.keys() I can only access "questions" or "q1" or type, text, qId etc. I can not pass all object properties at once and specify what I need in a child component.
"questions": {
"q1": {
"qId": "1",
"type": "YN",
"text": "Text 1",
"tip": {
"logo": "assets/icons/gadgetz.svg",
"logofallback": "assets/img/gadgetz.png",
"heading": "Heading 1",
"text": "Text 2"
}
},...
What would be the easiest way to pass the whole object with child properties so I can use these in a child component? do I have to use something other than props?
const questionObjects = Object.values(JSON.stringify(theJSONinYourQuestion));
const questionComponents = questionObjects.map(question => <Question qId={question.qId} />);
Basically, use Object.values instead of Object.keys, and you've got a nice array of questions you can use.
Edit: if you don't have Object.values available in your environment (it is experimental)
const originalQuestions = JSON.stringify(theJSONinYourQuestion);
const questionKeys = Object.keys(orginalQuestions);
const questionObjects = questionKeys.map(key => originalQuestions[key]);
...
You can maintain access to the question object inside of a .map by assigning it to a variable outside that scope. Here's a jsBin showing the idea
const objectOfQuestions = {
"questions": {
"q1": {
"qId": "1",
"type": "YN",
"text": "Text 1",
"tip": {
"logo": "assets/icons/gadgetz.svg",
"logofallback": "assets/img/gadgetz.png",
"heading": "Heading 1",
"text": "Text 2"
}
},
"q2": {
"qId": "2",
"type": "YN",
"text": "Text 1",
"tip": {
"logo": "assets/icons/gadgetz.svg",
"logofallback": "assets/img/gadgetz.png",
"heading": "Heading 1",
"text": "Text 2"
}
}
}
}
const Question = ({ id, question }) => {
return (
<div>
<h1>Question: {id}</h1>
<p>id: {question.qId}</p>
<p>type: {question.type}</p>
<p>text: {question.type}</p>
</div>
)
}
const QuestionList = ({ questions }) => {
const questionObj = questions;
return (
<div>
{Object.keys(questions.questions).map((key, i) => {
return (
<div key={key}>
<Question id={key} question={questionObj.questions[key]} />
</div>
);
})}
</div>
);
}
ReactDOM.render(<QuestionList questions={objectOfQuestions} />, document.getElementById('app'));