Reputation: 421
The result I want is this
<ul id="toc">
<li><Link to="/page1">Page 1</Link></li>
<li><Link to="/page1">Page 2</Link></li>
<li><Link to="/page1">Page 3</Link></li>
<li><Link to="/page1">Page 4</Link></li>
<li><Link to="/page1">Page 5</Link></li>
</ul>
its a lot so I want to loop through and make the links
const pages = [
{ name: "Page 1", url:"/page1"},
{ name: "Page 2", url:"/page2"},
{ name: "Page 3", url:"/page3"},
{ name: "Page 4", url:"/page4"}
]
now in my JSX
<ul id="toc">
{Object.keys(pages).map((name, url) => {
<li><Link to="{url}">{name}</Link></li>
})}
</ul>
However I am not seeing anything, I am not seeing the loop? is this the way to do it in JSX
Sorry for the layman q I am still new to react/js
Upvotes: 0
Views: 532
Reputation: 161517
Four little things that add up:
Object.keys(pages).map((name, url) => {
<li><Link to="{url}">{name}</Link></li>
})
pages
is already an array, Object.keys
is not necessary.name
and url
you can use destructuring. They aren't passed as the function params..map
needs to return a value somehow.{url}
.That all comes together as
pages.map(({name, url}) => {
return <li><Link to={url}>{name}</Link></li>
})
or
pages.map(({name, url}) =>
<li><Link to={url}>{name}</Link></li>
)
Upvotes: 2
Reputation: 747
Good Day , the code for that is this :
pages.map((page,index)=> {
<li><Link to={page.url}>{page.name}<Link></li>
})
once you map , the first element would be the name of each variable on the array.
imagine :
foreach (var page in pages)
wherein: pages is the list of page ( an array )
Upvotes: 1