Access and Display Nested Array on Screen React Native
Access and Display Nested Array on Screen React Native
I have an array of Athletes objects that contain another array of teams objects that particular athlete has played for:
Athletes
teams
var athletes = [
"athlete_id": 123,
"first_name": "john",
"last_name": "doe",
"teams": [
"team_id": 4,"team_name": "Eagles" ,
"team_id": 7, "team_name": "Knights"
]
,
"athlete_id": 276,
"first_name": "jane",
"last_name": "doe",
"teams": [
"team_id": 4,"team_name": "Pilots" ,
"team_id": 7, "team_name": "Thunder"
]
];
I want to, very simply, render the items in this format (teams listed under full name):
John Doe
Eagles
Knights
Jane Doe
Pilots
Thunder
I have tried the following in the render()method:
render()
<View>
athletes.map((item, key) =>
return <Text key=key>item.first_name + " " + item.last_name</Text>
item.teams.map((unit, key2) =>
return <Text key=key2>unit.team_name</Text>
)
)
</View>
With the above snippet of code, I have only been able to render the full names of both athletes, and not their teams. What can I do to achieve the proper output?
athletes
1 Answer
1
It is because you are returning the item with the first name, last name in it, before your code has chance to return any of the team data:
<View>
athletes.map((item, key) =>
return (
<View key=key>
<Text>item.first_name item.last_name</Text>
item.teams.map((unit, key2) =>
return <Text key=key2>unit.team_name</Text>
)
</View>
);
)
</View>
My bad, the returned jsx needs a single parent element, edited answer to add top level div.
– Chris Cousins
Aug 28 at 19:55
I was able to get it working by replacing <div> with <View>. I also shifted ' key=key ' from the <Text> component to the <View> component to resolve a warning that was previously appearing. Appreciating that your answer seems to be the ReactJS equivalent to the solution, I have marked it as the accepted answer. Thanks!
– hb22
Aug 29 at 3:28
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I am having an issue with using return(); within the map function. [ Error: unexpected token, expected , ]. This is not a problem when I use single line "return … "
– hb22
Aug 28 at 19:52