Modeling a tree-structure taxonomy in Sanity for Norwegian regions

8 replies
Last updated: Mar 30, 2021
Hi all!
New to Sanity
🙂
How would I model a tree-structure taxonomy of pre-defined values?

I can make a simple one-level taxonomy with an array of strings, with the strings pre-defined.

But I want to make a tree-structure where you can choose the whole category (parent), or a child, or even a grand-child. Is this possible?

My use case is Norwegian counties and municipalities, where I want the user to be able to select:

• The whole country
• Any number of specific counties, say Viken
• Any number of specific sub-counties / municipalities, say Fredrikstad (all of these belong to a county)
Any leads on how to do this easily?
Mar 23, 2021, 8:12 AM
Later I will want to filter on these, so that I can say "Show me all content in the county Viken" and it'll know that all the documents marked with the sub-county "Fredrikstad" are also in Viken.
Mar 23, 2021, 8:15 AM
I guess at least the “tree selection” part could be with a custom input component?
Mar 23, 2021, 8:28 AM
Basically I want it to function like the finn.no area selector:
Mar 23, 2021, 8:35 AM
Found a sort of solution, though it doesn’t feel like the most elegant one
Mar 23, 2021, 9:08 AM
Proof of concept code:

const viken = {
  name: 'vikenSelector',
  title: 'Viken',
  type: 'object',
  options: {
    collapsible: true,
    collapsed: true,
  },
  fields: [
    {
      title: 'Hvor i Viken?',
      name: 'vikenOverview',
      type: 'array',
      options: {
        list: [
          { title: "Hele viken", value: "viken" }, 
          { title: "Fredrikstad", value: "fredrikstad" }, 
          { title: "Moss", value: "moss" } 
        ]
      },
      of: [
        {
          type: 'string'
        }
      ]
    }
  ]
}

const fylkeTest = {
  name: 'where',
  title: 'Hvor?',
  type: 'object',
  fields: [
    viken
  ]
}
Mar 23, 2021, 9:09 AM
Ugly on output though:
Mar 23, 2021, 9:13 AM
Hey User! I think conditional fields might help you clean this up a bit. Here’s a blob with the basics of one.
Mar 23, 2021, 3:27 PM
Thank you User!
Mar 30, 2021, 5:14 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?