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>
)
Related
What I am trying to do is fetch the inner data of blog_set. But in my case, I'm getting a null value (usually nothing is output).
Is this the correct way to get the value: {bloglist.blog_set.title} ?
api-data:
[
{
"url": "http://localhost:8000/api/category/brown",
"id": 1,
"title": "brown",
"slug": "brown",
"image": "http://localhost:8000/media/category/bg_1.jpg",
"description": "",
"created_on": "2020-05-08T15:21:02Z",
"status": true,
"blog_set": [
{
"id": 6,
"url": "http://localhost:8000/api/blog_detail/test3",
"title": "test3",
"slug": "test3",
"image": "http://localhost:8000/media/blog/author.jpg",
"description": "test3",
"created_on": "2020-05-13T13:36:45Z",
"status": true,
"category": [
1
]
}
]
}
]
./src/Category.js
export default class App extends Component{
state = {
bloglist: [],
};
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
try {
const response = await fetch("http://localhost:8000/api/category");
const jsonResponse = await response.json();
this.setState({ bloglist: jsonResponse });
} catch (error) {
console.log(error);
}
};
render(){
{
const { bloglist } = this.state;
return(
<div>
{bloglist.map((bloglist) => (
<div>
<h3 class="mb-2">{bloglist.blog_set.title}</h3>
</div>
))}
</div>
);
}
}
}
blog_set is an array so it does not have an attribute/memeber/item called title. You should define at what index you want the data.
bloglist.blog_set[0].title
Or iterate over blog_set too
As bloglist is also an array you need to use one more .map() or as bloglist[0].blog_set[0].title
Example:
{bloglist.map((bloglist) => (
<div>
<h3 class="mb-2">{bloglist.blog_set.map(i=> i.title)}
</h3>
</div>
))}
blogList.map() will iterate the parent Array of objects to get blog_set and blog_set.map() will now iterate the blog_set to get list title
{bloglist.map((bloglist) =>(
<div>
<h3 class="mb-2">{bloglist.blog_set.map((list)=>( list.title)}</h3>
</div>)}
blog_set is an array. In order to iterate it, use map and {title}. In each iteration of your blog_set object, there is a key named title (destructured object).
<div>
{bloglist.map((bloglist) => (
<div>
<h3 class="mb-2">{blog_set.map(({title})=>title))}</h3>
</div>
))}
</div>
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>
);
}
I have the bellow alike data, and I would like to render them.
Let's say I would like to display firstName, address, and seatType and flightId for each flight the passenger has.This has to be done for each passenger. How can I achieve that?
Updated
[
{
"id": 1,
"firstName": "Smith",
"lastName": "John",
"address": [
"1 Street",
"YYY",
],
"flights": [
{
"flightId": 1,
"seatType": "oridinary"
},
{
}
]
},
{},
]
Here is my code
render() {
const { data } = this.state;
return (
<div>
{" "}
{Object.keys(data).map((key, index) => (
<p key={index}>
{" "}
{key} {data[key].flights}
{data[key].flights.map(k => (
{data[key].flights[k]}
))}
</p>
))}
</div>
);
}
I'm assuming you're looking for something like this:
return (
<div>
{
passengers.map(passenger => {
if (!passenger.id) { return null } /* + */
return (
<div key={passenger.id}>
<span>{passenger.firstName} {passenger.lastName}</span>
<div>
<span>Passenger's Flights</span>
{
passenger.flights && /* + */
Array.isArray(passenger.flights) && /* + */ passenger.flights.map(flight => {
if (flight.flightId) {
return (
<div key={flight.flightId}>
{flight.seatType}
</div>
)
}
return null
})
}
</div>
</div>
)
})
}
</div>
);
}
Note: remember that you should not use index as a key.
Edit: You need to add a null/undefined check
render() {
const { data } = this.state;
return (
<div>
{data.map((passenger, index) => (
<p key={index}>
{passenger.firstName} {passenger.address.join(' ')}
{passenger.flights.map(flight => (
<p>{flight.seatType} {flight.flightId}</p>
))}
</p>
))}
</div>
);
}
render() {
const { data } = this.state;
return (
<div>
{data.map(({id, firstName, address, flights}) => (
<p key={id}>
<div>{firstName}</div>
<div>{address.join(', ')}</div>
{flights.map(f => (<div key={f.flightId}>{f.flightId}-{f.seatType}</div>))}
</p>
))}
</div>
);
}
Not sure if it compiles but it's something like this. Also, if you have an ID, use it as key.
I have an object skills and I want to iterate over it and map its contents. The object looks like this:
{
"_id": {
"$oid":"5d85b311e180652980824193"
},
"date":{
"$date":{ "$numberLong":"1569043209148" }
},
"title": "test",
"image":"test image",
"description":"test desc",
"__v":{
"$numberInt":"0"
}
}
I am using MongoDB
and my mapping looks like this:
componentDidMount() {
this.props.fetchSkills();
}
render() {
const { skills } = this.props
let skillData
if (skills.length === 0) {
return (
<p>There are no skills to display</p>
)
} else {
skillData = skills.map(skill => (
<div key={skill._id}>
<div>
<img src={skill.image} alt="" />
</div>
<div>
<h2>{skill.title}</h2>
<div>
<span>{skill.date}</span>
</div>
<div>
<p>{skill.description}</p>
</div>
</div>
</div>
))
}
return (
<div>
{skillData}
</div>
)
}
However, I get this error when I load the page:
TypeError: skills.map is not a function
26 | )
27 | } else {
28 |
> 29 | skillData = skills.map(skill => (
30 | ^
31 | <div className="item" key={skill._id}>
32 |
I think it's because .map can only iterate through arrays but I am trying to iterate through an object.
You need to have an array, to be able to iterate through it using the function .map()
So simply transform your object in an array of objects like this:
[
{
"_id": {
"$oid":"5d85b311e180652980824193"
},
"date":{
"$date":{ "$numberLong":"1569043209148" }
},
"title": "test",
"image":"test image",
"description":"test desc",
"__v":{
"$numberInt":"0"
}
}
]
And now you'll be able to successfully use .map()
Forgive me, I'm a react noob. I'm trying to access the data inside a javascript/react object. The json data looks like this:
"schoolData": {
"student": [
{
"name": "blah",
"type": "lorem",
"grade": 90,
}
],
"class": null
},
What I'm trying to display is essentially just like this...
Student
name: Blah type: lorem grade: 90
Class
--- no data here ---
So I'm trying like this:
import React, { PropTypes } from 'react';
const SchoolDataPropTypes = {
SchoolData: PropTypes.object.isRequired,
};
function School(props) {
return (
<div className="section">
<h3 className="head">School Data</h3>
<div className="row">
<ul className="Uli">
{(props.data || []).map(function(value) {
return <label>{props.data.key}</label><li key={value}>{key}: {value}</li>
})}
</ul>
</div>
</div>
);
}
School.propTypes = SchoolPropTypes;
export default School;
It obviously doesn't work. So that I can render each array inside the object?
Ideally, you would manually specify each key.
{(schoolData.student || []).map(student => (
<ul className="Uli">
<li>Name: {student.name}</li>
<li>Grade: {student.grade}</li>
</ul>
))}
etc...
But if you really want to loop through variable keys in the student object then basically you need to loop through the student array, and then loop through the keys in each student object. Here's what it might look like:
const School = ({ schoolData }) => (
<div className="section">
<h3 className="head">School Data</h3>
<div className="row">
{(schoolData.student || []).map(student => (
<ul className="Uli">
{Object.keys(student).map(key => (
<li key={key}>{key}: {student[key]}</li>
))}
</ul>
))}
</div>
</div>
);
-
<School schoolData={schoolData} />
If you're targeting very, very old browsers you may need a polyfill for Object.keys