简体   繁体   中英

How can I loop through to make a list with a Link?

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

Four little things that add up:

Object.keys(pages).map((name, url) => {
  <li><Link to="{url}">{name}</Link></li>
})
  1. Since pages is already an array, Object.keys is not necessary.
  2. To get name and url you can use destructuring. They aren't passed as the function params.
  3. The function passed to .map needs to return a value somehow.
  4. You can leave out the quotes around {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>
)

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM