Reputation: 1117
I am trying to map
through a nested Array
using JSX
.
Here is the Array
:
this.topics = [
{
id: 1,
name: 'first',
headings : [
{
id: 1,
url: 'https://media.w3.org/2010/05/sintel/trailer.mp4',
name: 'Sintel movie'
},
{
id: 2,
url: 'https://media.w3.org/2010/05/bunny/movie.mp4',
name: 'Bunny Movie'
},
{
id: 3,
url: 'https://techslides.com/demos/sample-videos/small.mp4',
name: 'Test page'
}
]
},
{
id: 2,
name: 'second',
headings : [
{
id: 1,
url: 'https://media.w3.org/2010/05/sintel/trailer.mp4',
name: 'Siddntel movie'
},
{
id: 2,
url: 'https://media.w3.org/2010/05/bunny/movie.mp4',
name: 'Bunnddy Movie'
},
{
id: 3,
url: 'https://techslides.com/demos/sample-videos/small.mp4',
name: 'Test ddpage'
}
]
}
];
And the JSX
code that I have come up with so far:
renderSidenav(){
return(
<Nav>
{this.topics.map(topic =>
<Dropdown eventKey="3" title="s" icon={<Icon icon="magic" />}>
{this.topics[topic].headings.map(heading =>
<div onClick = {() => this.handleSelect(heading.id)} key={heading.id}>
<Dropdown.Item style={{backgroundColor: '#E9F4E4'}} icon={<Icon icon="dashboard"/>}>
<div>{heading.name}</div>
</Dropdown.Item>
<Dropdown.Item divider style={{backgroundColor: 'white', height: '2px'}}/>
</div>
)}
</Dropdown>
)}
</Nav>
)
}
And this is the error I get:
TypeError: Cannot read property 'headings' of undefined
What am I doing wrong?
Upvotes: 0
Views: 75
Reputation: 7049
Instead of this.topics[topic].headings.map(...)
use topic.headings.map(...)
This is because .map()
returns an object, and trying to use it as an index via topics[topic]
will give you undefined
.
Upvotes: 1
Reputation: 632
Just do topic.headings.map
instead of this.topics[topic].headings.map
.
Map function returns the item, not the position/index in the array, therefore you can call it directly from topic
.
Upvotes: 1