React render data with array index - javascript

I have facing an issue in React js, I want to render all data from rest API and show with a numeric index.
Rest API:
[
{
"id": "1",
"start_date": "2020-05-08 09:45:00",
"end_date": "2020-05-08 10:00:00",
"full_name": "mirza",
"cust_full_name": "furqan",
},
{
"id": "2",
"start_date": "2020-05-08 02:45:00",
"end_date": "2020-05-08 03:00:00",
"full_name": "mirza",
"cust_full_name": "ahmed",
},
{
"id": "3",
"start_date": "2020-05-08 06:45:00",
"end_date": "2020-05-08 07:00:00",
"full_name": "mirza",
"cust_full_name": "ali",
}
]
my code:
render()
{
let FullNameSlot1 = null //FullNameSlot
let SecondFullNameSlot1 = null
let BaberNameSlot1 = null //BaberNameSlot
let SecondBaberNameSlot1 = null
if (this.state.appointmentdata && this.state.appointmentdata.length
this.state.appointmentdata[0].start_date.toString() > this.state.newprevious
)
{
FullNameSlot1 = (
<p key={0}>{this.state.appointmentdata[0].cust_full_name}</p>
)
BaberNameSlot1 = (
<p key={0}>{this.state.appointmentdata[0].full_name}</p>
)
}
i want to render data with array {index}
if (this.state.appointmentdata && this.state.appointmentdata.length
this.state.appointmentdata[1].start_date.toString() > this.state.newprevious
)
{
SecondFullNameSlot1 = (
<p key={1}>{this.state.appointmentdata[1].cust_full_name}</p>
)
SecondBaberNameSlot1 = (
<p key={1}>{this.state.appointmentdata[1].full_name}</p>
)
}
I want to render all data from rest API and show with a numeric index. Make my code it simple.
<p key={index}>{this.state.appointmentdata[index][0].cust_full_name}</p>
<p key={index}>{this.state.appointmentdata[index][1].cust_full_name}</p>
Demo:
https://codesandbox.io/s/agitated-elion-quqp1
What should i do? Any one help me?

You can use conditional rendering and your final condition is a ternary to either map the array of data to JSX or return null. The array::map first argument is the current element being iterated, and the second argument is the current index. When returning JSX like this though you need to return a single node. Here I've used a react Fragment and attached the key there. I also destructured the element properties you wanted to display.
Conditional Rendering
Lists and Keys
{
(this.state.appointmentdata &&
this.state.appointmentdata.length &&
this.state.appointmentdata[1].start_date.toString() > this.state.newprevious)
? this.state.appointmentdata.map(({ cust_full_name, full_name }, index) => (
<Fragment key={index}>
<p>{cust_full_name}</p>
<p>{full_name}</p>
</Fragment>
) : null
}

#adnan khan Welcome to Stackoverflow! to render an array of elements you can make use of Array.map function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
In your example it might look like this
if(this.state.appointmentdata && this.state.appointmentdata.length){
this.state.appointmentdata.map((data ,index) => <p key={index}>{data.cust_full_name}</p> )
}

If you want to render elements dynamically then conditional rendering is an option
You can use map() on appointmentdata and create the same number of elements as objects in the result of API
Sample:
render() {
return (
<React.Fragment>
{
this.state.appointmentdata.length
?
this.state.appointmentdata.map(ele => {
return (
<React.Fragment>
<p key={`cf_${ele.id}`}>{ele.cust_full_name}</p>
<p key={`f_${ele.id}`}>{ele.full_name}</p><hr/>
</React.Fragment>
)
})
: "__"
}
</React.Fragment>
);
}

Related

how to render a nested array and string in an object which is further nested in an array

I am trying to render the data called items in nextjs and I have been debugging it for a while. below is my code that causes the error. the goal is to render the descriptions in an array as alist and render the description that is a string as it is but i can not use the map function because of the fist description(which is a string). I am also trying to not use dangerouslysetinnerhtml.
export default function SingleCareerContainer(){
const items = [
{
title: "About",
description:
"We are developing new functionality for an application },
{
title: "Requirements",
description: [
"3+ years of working experience.",
"Extensive experience in Swift. ",
"mobile development life cycle.",
"good communication skills.",
],
},
{
title: "Responsibilities",
description: [
"write program code according to the defined application architecture.",
"Implement code refactoring. ",
"refactoring and optimization results. ",
"Develop, document, and edit programming interfaces.",
"Estimating tasks .",
],
},
{
title: "What we Offer",
description: [
"Above average compensation.",
"Close cooperation.",
"Challenging tasks. ",
],
},
];
for (const item of items) {
let rep = item.description;
if(rep.length > 1){
const ree = rep.map((reps, i) => {
return(
<Text key={i}>{reps}</Text>
)
})
}else{
return(ree);
}
const itemcomp = items.map((item, i) => {
return (
<>
<div>
<p>
{item.title}
</p>
</div>
</>
);
});
return (
<>
<Container>
<p>
Frontend Developer
</p>
<Button width={"auto"} height={"60px"}>
Apply
</Button>
<>
<p>
<div>{itemcomp}</div>
{ree}
</p>
</>
</Container>
</>
);
}
`
A string is also an array under the hood so you can't reliably distinguish between an array and a string with .length property. You need to use typeof operator because an array has 'object' value while string has 'string' value if you apply it to both types.
Pseudo-code:
if (typeof description === 'string') {
return description
} else {
return description.map(item => <Text>item</Text>)
}

Avoid duplication in React array map function [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 8 months ago.
I am fetching some data in form of strings , and I would like to avoid any duplication when I map this array .
This is how I am using this function in React :
<Flex >
{allPrismicCollection.nodes.map((collection)=>
(
<Navbar>
<NavTitle>{collection.data.collection.text}</NavTitle>
<NavbarFlex>
{collection.data.slides.map((coll)=>
<>
{coll.slide.document.data.blogs.map((s)=>
<>
{s.blog.document.data.tags.map((t)=>
(
<NavLink><Link to='#'>{t.tag}</Link></NavLink>
)
)}
</>
)}
</>
)}
</NavbarFlex>
</Navbar>
)
)}
</Flex>
This is the JSON format of the array , it contains multiple blog fields and each field has various tags fields .
"blogs": [
{
"blog": {
"document": {
"id": "4a007c39-2053-5c5e-8f38-56ba8c3aced5",
"data": {
"tags": [
{
"tag": "Entertainment"
},
{
"tag": "Happiness"
},
{
"tag": "Philosophy"
}
]
}
}
}
},
{
"blog": {
"document": {
"id": "9e78be5c-08e7-5684-adaa-b788cb4020b7",
"data": {
"tags": [
{
"tag": "Life"
},
{
"tag": "Vacation"
},
{
"tag": "Drama"
}
]
}
}
}
}
]
}
}
}
},
When consoling s.blog.document.data.tags I get multiple arrays , I need to wrap them in a single array based on the collection name !
the t.tag will return some duplicated values and I don't want it , how can I solve this please ?
You can use a package named lodash installable via npm or yarn. Then import the uniq function to use.
E.g.
import { uniq } from 'lodash'
Your code should then look like this
{uniq(s.blog.document.data.tags).map((t)=>
(
<NavLink><Link to='#'>{t.tag}</Link></NavLink>
)
)}
If t is an object, like in your case then you will need to use uniqBy function instead.
import { uniqBy } from "lodash"
Then your code should be
{uniqBy(s.blog.document.data.tags, 'tag').map((t)=>
(
<NavLink><Link to='#'>{t.tag}</Link></NavLink>
)
)}

How Do i Iterate through a JSON object in ReactJS?

On my ReactJS file, I JSON.stringify my object to see what i get.
return (
<div>
{ JSON.stringify(peopleChannel) };
</div>
)
I get return something like this
{
"Y3WJb6": {
"photoURL": "https://myimage.com",
"email": "abc.com"
},
"Yzfd6": {
"photoURL": "https://myimage23.com",
"email": "adfasfd.com"
}
}
How do I render it into like a list?
You can map over Object.values(peopleChannel), or if you need the object keys as well use Object.entries:
return (
<div>
{Object.entries(peopleChannel).map(([id, {photoURL, email}]) => (
<div>
<div>{id}</div>
<div>{photoURL}</div>
<div>{email}</div>
</div>
))}
</div>
)

Properly filter an array inside other array in reactjs

Hello I am trying react for the first time and I am having some trouble with my filter function.
Here's the code:
So this is my render method in my component:
const categoryFilter = this.state.appItems.filter(item =>
item.categories.filter(str => {
return str.includes(active);
})
);
const appList = categoryFilter.map(appItem => (
<AppItem appItem={appItem} key={appItem.id}></AppItem>
));
return (
<React.Fragment>
<div className="flex-container">
<NavCategories
categories={this.state.categories}
onClick={this.handleClick}
active={active}
/>
<section className="apps-list">
<header>
<input type="text" placeholder="Search by App" />
</header>
<ul>{appList}</ul>
</section>
</div>
</React.Fragment>
);
this.state.appItems is an array coming from a json file, here's a snippet:
[ {
"id": "12312",
"name": "Test",
"description": "test.",
"categories": ["Voice", "Delivery", "Optimization"],
"subscriptions": [
{
"name": "Trial",
"price": 0
},
{
"name": "Professional",
"price": 3500
}
]
},]
Active is a string to manage active class items on another component.
Everything renders correctly, but it is never filtered even though the active state is changing everytime.
I have tried multiple ways, but this Filter method is getting me confused a lot because I want to filter an array thats inside another array and want to filter the whole AppItem array.
If anyone could explain/give me some tips I would love it. Thanks in advance :)
Array.filter() returns a new array with the filtered elements in it. So your inner filter will always return an array of at least zero elements, which evaluates to a truthy value, and your outer filter will just include every element in the original array.
Just switch your inner filter to be an Array.includes() instead, which will return true or false.
const categoryFilter = this.state.appItems.filter(item =>
item.categories.includes(active)
);

Unable to render the JSON Object on browser in React.js

I am trying to display a JSON object which is an array in React. I am able to write the React code for doing that. However, I am not able to see the output in my browser.
Here is my code:
import React, {Component} from 'react';
import data from '../articles';
export default class fetchData extends Component {
showData = (inputValue) => {
inputValue.forEach((temp) => {
return (
<h1> temp.article_id </h1>
);
});
}
render () {
return (
<h1> {this.showData(data)} </h1>
);
}
}
JSON object: (located in ../articles)
[
{
"article_id": "101",
"org_id": "10001",
"reported_by": "Srilakshmi",
"reported_on": "11-16-2016",
"author": "Sree",
"language": "English",
"src_url": "",
"key_words": "CS, Programming",
"status": "Draft",
"channel_ids": "IOE1",
"title": "CS 101 Lession",
"description": "CS 101 First Lession",
"file_on_disk": "",
"publish_on": "",
"Published_on": "",
"contentArray": ""
},
{
"article_id": "102",
"org_id": "10001",
"reported_by": "Srini",
"reported_on": "11-16-2016",
"author": "Srini",
"language": "English",
"src_url": "",
"key_words": "CS, DB",
"status": "Draft",
"channel_ids": "IOE2",
"title": "CS DB 101 Lession",
"description": "CS DB 101 First Lession",
"file_on_disk": "",
"publish_on": "",
"Published_on": "",
"contentArray": ""
}
]
Any help with getting the data to display would be highly appreciated.
3 mistakes here...
First:
<h1> temp.article_id </h1> won't print article ID. Use curly braces to print actual value
<h1>{ temp.article_id }</h1>
Second:
forEach array method just loops array, it does not create new one from values returned in callback. Use map method instead.
inputValue.map((temp) => {
return (
<h1> temp.article_id </h1>
);
});
Third:
you are not returning from showData method at all.
Edit your code to return newly created array of components (that array created using map method)
showData = (inputValue) => {
return inputValue.map((temp) => {
return (
<h1>{ temp.article_id }</h1>
);
});
}
Bonus:
make it short using arrow functions
showData = (inputValue) =>
inputValue.map(temp => <h1>{ temp.article_id }</h1>)

Categories