How to map over nested arrays to output link urls in React

7 replies
Last updated: Dec 9, 2022
I have a query returning:

0:{…} 8 properties
_createdAt:2022-12-07T23:19:09Z
_id:navigation
_rev:Bp455s9rtQ49wRO6vY4ZPz
_type:navigation
_updatedAt:2022-12-08T21:58:33Z
items:[…] 1 item
0:{…} 4 properties
_key:7f41faf793a8
_type:navigationItem
navigationItemUrl:{…} 2 properties
_type:link
internalLink:{…} 2 properties
text:login
navId:{…} 2 properties
_type:slug
current:mainMenu
title:Browse
I'm able to display the title "Browse" with


{navs.map((navs: any) => (
        <div key={navs._id}>{navs.title}</div>
      ))}
But I want to use navigationItemUrl's "text" in a map to output link urls.

How might I go about this?
Dec 8, 2022, 11:59 PM
Ok, update!
I have gotten the "text" ("login") to show up in the link this way:

{navs.map((navs: any) =&gt; (
&lt;div key={navs._id}&gt;
&lt;a href={
/${navs.items[0].text}
}&gt;TEXT&lt;/a&gt; &lt;/div&gt;
))}

But I've added another item:


0:{…} 8 properties
_createdAt:2022-12-07T23:19:09Z
_id:navigation
_rev:cwf6PSmkIH3MXtFHyvxJDS
_type:navigation
_updatedAt:2022-12-09T00:18:00Z
items:[…] 2 items
0:{…} 4 properties
_key:7f41faf793a8
_type:navigationItem
navigationItemUrl:{…} 2 properties
_type:link
internalLink:{…} 2 properties
_ref:783ff653-fa25-4caa-ad69-dcf78dcaa970
_type:reference
text:login
1:{…} 4 properties
_key:85a628a4890b
_type:navigationItem
navigationItemUrl:{…} 2 properties
_type:link
internalLink:{…} 2 properties
_ref:b4d875e5-798e-401f-ac30-8b4ad96ecb82
_type:reference
text:blog
navId:{…} 2 properties
_type:slug
current:mainMenu
title:Browse
And I want to have the map output them both... What do I do?
Dec 9, 2022, 12:25 AM
You’ll want to map over that
items
array. I may have made up a
_key
value that’s not in your content, but perhaps something like:
{navs.map((nav) => (
  <div key={nav._id}>
    {nav.items.map((item) => (
      <a key={item._key} href={`/${item.text}`}>TEXT</a>
    ))}
  </div>
))}
Dec 9, 2022, 12:40 AM
user A
Ok, let me try that - I'll get back to you
Dec 9, 2022, 12:41 AM
user A
It works! YOU'RE BRILLIANT!!!!
Dec 9, 2022, 12:42 AM
Side note... so many maps... Is this normal?
Dec 9, 2022, 12:43 AM
Yes, if you have an array nested in an array, you’ll need to map over both. Depending on your setup you may want to add some guards (for example, what happens if
items
is empty? What if
navs
is empty?), but otherwise this should be fine and is completely typical.
Dec 9, 2022, 12:59 AM
user A
Brilliant, thank you!
Dec 9, 2022, 1:09 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?