Querying and hooking up a navigation schema to a front end in Sanity.io

7 replies
Last updated: Sep 29, 2022
I followed this tutorial for making a navigation schema: https://www.sanity.io/guides/creating-navigation-schema but I don't think the next step of hooking it up to a front end is done yet, so I was trying to figure it out on my own
I can query the navigation type like this
*[_type == 'nav' && id == 'main'][0] { title, id, navItems }
which returns results like:

{
  "ms": 26,
  "query": "*[_type == 'nav' && id == 'main'][0] { title, id, navItems }",
  "result": {
    "id": "main",
    "navItems": [
      {
        "_key": "1371ba23535c",
        "_type": "navItem",
        "navItemUrl": {
          "_type": "link",
          "externalContent": false,
          "internalLink": {
            "_ref": "hfksghkjsghkjlhagjghaghasdag",
            "_type": "reference"
          }
      },
    "text": "Home"
  },
...
}
for external links I could easily get the url, but with internal pages, how do you follow the reference to get the url of the page?
Sep 29, 2022, 3:34 PM
Sep 29, 2022, 3:46 PM
I gathered that I need to somehow use this
->
operator, I've been trying but can't figure out how it fits into the query
Sep 29, 2022, 3:48 PM
also navItems is an array, so the query needs to get into the array, which maybe also what's hanging me up, and then inside the array I need to expand the reference to internalLink ?
Sep 29, 2022, 3:50 PM
Untested but it will be something like this:
*[_type == 'nav' && id == 'main'][0] {
  title,
  id,
  navItems[] {
    ...,
    internalLink->
  }
}

Sep 29, 2022, 3:52 PM
ok cool, that makes sense
Sep 29, 2022, 3:56 PM
Thanks! here's the query I ended up with:
*[_type == 'nav' && id == 'main' ][0]{ 
  title, 
  id,
  navItems[] {
    text,
    navItemUrl {
      externalContent, externalLink, internalLink-> {
        'slug': slug.current
      }
    }
  }
}

Sep 29, 2022, 4:06 PM
so when I was trying to hook this up to a navigation component I started doing some conditional logic to handle the internal versus external links and I realized I could simplify the front end code if I could do that in the query like
*[_type == 'nav' && id == 'main' ][0]{ 
    title, 
    id,
    navItems[] {
      text,
      externalContent,
      'url': select(
        navItemUrl.externalContent => navItemUrl.externalLink,
        navItemUrl.internalLink-> slug.current
      )
    }
}
Sep 29, 2022, 7:31 PM

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?