How can I extract data from complex JSON file with reactJS? - json

I am new to reactJS. I have a JSON file which looks like this:
I want to extract data and display each post with its comments, user who commented and created time and display it with JSX using the map function.
So I declared an empty array called items in my state and put all these data into it and tried to browse it but I got this error:
×
TypeError: Cannot read property 'data' of undefined
this is my code:
render() {
return (
<div>
<h1>Hello World !!!! </h1>
<ul>
{ this.state.items.comments.data.map(item => <li key={item.id}>{item.data[item].from.name}</li>)}
</ul>
</div>
)
}

Nice to meet you.
I can solve it.
Please do like below.
render() {
return (
<div>
<h1>Hello World !!!! </h1>
<ul>
{ this.state.items.comments.data.map(item => <li key={item.id}>{item.from.name}</li>)}
</ul>
</div>
)
Please reply with your opinion.
Best regards.

in your json file look like you get array of array
try with this hope this will work
this.state.items.map((item,index)=>{
this.state.items[item].comments.data.map(element=>
<li key={item.id}>{item.from.name}</li>)
})
})

I figured out that I have to use map inside another map because I have an array in another array and this code solved the problem:
render{
return (
<div>
{
this.state.items.map((item) => {
return (
<div>
<h4>{item.id}</h4>
<ul>
{
item.comments.data.map((data) => {
return (
<li>
{data.message} : {data.created_time} : {{data.from.name}
</li>
);
})
}
</ul>
</div>
);
})
}
</div>
);
}

Related

graphql query not rendering to page

console.log(data.allShopifyProductVariant.nodes[0].product.title)
return (
<div>
<div>
{data.allShopifyProductVariant.nodes.map(node => {
<div>
{node.product.title}
</div>
})}
</div>
</div>
)
}
export const query = graphql`
query CollectionQuery {
allShopifyProductVariant(filter: {product: {productType: {in: "20 lb. Plotter Paper"}}}) {
nodes {
compareAtPrice
sku
price
product {
title
images {
gatsbyImageData(width: 150)
}
productType
}
}
}
}`
export default Collection;
Expecting this function to return the product title, for some reason it returns nothing. I've tried using dangerously set innerhtml but nothing comes up, no error. I am able to console.log the {node.product.title} and it returns exactly what I want to display but for some reason it is not rendering to the div. Any help is appreciated, thanks in advance :D
You are missing the return statement:
return (
<div>
<div>
{data.allShopifyProductVariant.nodes.map(node => {
return <div>
{node.product.title}
</div>
})}
</div>
</div>
)
Or using the implicit return:
return (
<div>
<div>
{data.allShopifyProductVariant.nodes.map(node => (
<div>
{node.product.title}
</div>
))}
</div>
</div>
)

ReactJs App's mapped list of buttons from Json file only have the last value of json array

I am making list of button that will lead to different YouTube videos on ReactJs page. The issue is that when I map the links from json file (which contains video links), all the buttons get the last link of the mapped array. I need a way that all the rendered buttons will get their respective links. My code is below, I am using react ModalVideo to show my YouTube video.
<ul className="list-unstyled">
{datalist.lectures.map((value, index) => {
return (
<li key={index}>
<ModalVideo channel='youtube' autoplay isOpen={isOpen} videoId={value} onClose={() => setOpen(false)} />
<button className="play-icon" onClick={()=> setOpen(true)}> <i className="las la-play"></i> Lecture: {index+1}</button>
</li>
)})}
</ul>
All the links are coming from Json file where the code looks like this
"lectures": [
"BT4YihNXiYw",
"NSFLhnv2pQI",
"sEPxqpFZit8",
"fU8QhoUJ_sE",
"r3XFYOtvUng",
"MZAkMddxhpg"
]
I think the problem I have right now is that after the page render and mapping ends it only remembers what the last link is store in value, because of that no matter which button i click it shows me the last value of the mapped array
Just some quick ideas looking at the minimal snippets available.
let's not to render multiple ModalVideo component like above, move it out from the map.
Use another state to keep track the change of the youtube videos' ID.
For example
const [isOpen, setOpen] = useState(false);
const [videoId, setVideoId] = useState(null);
const playVideo = (vid) => {
setOpen(true);
setVideoId(vid);
};
return (
<div>
<ModalVideo
channel='youtube'
autoplay
isOpen={isOpen}
videoId={videoId}
onClose={() => setOpen(false)}
/>
<ul className="list-unstyled">
{
datalist.lectures.map((value, index) => {
return (
<li key={index}>
<button className="play-icon" onClick={() => playVideo(value)}>
<i className="las la-play"></i>
Lecture: {index + 1}
</button>
</li>
)
})
}
</ul>
</div>
);

Convert array of links into links - React

Im new to React. Im trying to convert an array contains links into something that will show the links in order in the website.
something like this:
external_references = ["https://google.com", "https://en.wikipedia.org/wiki/Wiki"]
into something to show up in the server like this:
external_references:
https://google.com(link)
https://en.wikipedia.org/wiki/Wiki(link)
I tried to do the following code I found but it failed to work:
<span className="externalRefs">External_references: <br></br> {external_references.forEach(link => {
return new DOMParser().parseFromString(link, "text/xml");
})}</span>
you can try the map function:
<p>external_references:</p>
{external_references.map(link=>{
return <div key={link}>
<a href={link}>{link}</a>
</div>
}
}
I recomend you as a good practice using the link as a key, since each of them should be different.
just
{external_references.map((reference, i) => {
return(
<div key ={i}>
<a href ={reference}>{reference}</a>
</div>
);
})}
You can use the Array.map function.
<span className="externalRefs">External_references: <br></br>
{
external_references.map(link, i) => {
<div key ={i}>
<a href ={link}>{link}</a>
</div>
}
}
</span>

how to get value from json object with its index number in reactjs like posts[2].title

from https://jsonplaceholder.typicode.com/posts
{ this.state.posts.map((post) => {
return (
<li>
<span>{post.title}</span>
</li>
);
})
}
it return all the title but how do I get post[1] or post[0] title
tried {post[0].title} not working
Thank you
Remove the map function and simply write
<li>
<span>{this.state.posts[0].title}</span>
</li>
You can pass the index with post inside function, it will help us to iterate over list of post.
{this.state.posts.map((post, index) => {
<li>
<span>{post[index].title}</span>
</li>
})
}
return should be before the map if you need it.
return (
{this.state.posts.map((post, index) => {
<li>
<span>{post[index].title}</span>
</li>
})
}
)

React Render HTML object from JSON object

I have to render html object Array in React JS
Can anyone guide me how to use renderHTML function.
output of the object is something like this:
"
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML("{item.albComEn}")}</div>
another variation i tried
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML("item.albComEn")}</div>
));
output i get => "item.albComEn"
or
{item.albComEn}
You can try with template strings. More info
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML(`${item.albComEn}`)}</div>
You can also use short syntax of React Fragments i.e. '<> </>'. Use these to bracket to write the html code. When rendered the html code will successfully compiled.
Example:
const service = [
{
htmlCode: <>
<div>
<h2>Application Screening</h2>
<br />
<br />
What you can expect from us:<br />
- Your resume will be written by a team of seasoned experts<br />
- They will make sure that your Resume presents your strong points,
achievements & key skills in a recruiter-friendly format.<br />
</div>
</>
},
]
Use inside render method as
...
render(
<div>
{service[0].htmlCode}
<div>
)
}