How to create a unique key for a static list in Gatsby using React and GraphQL
15 replies
Last updated: Jun 17, 2021
C
I have an
Arraycurrently which i query from graphql, and then I map it into a
<li>in Gatsby. However, React throws the missing
keyerror. I have no unique key within my
Array. How should I go about working around this? Do I create an object with two key value pairs, one that has an
idand the other with my
Array?
Jun 17, 2021, 3:21 AM
S
user R
normally in react, if you don’t have an ID you can just use the indexto do something like this:
return ( <ul> {items.map((item, index) => ( <li key={`item_${index}`}>{item}</li> ))} </ul> )
Jun 17, 2021, 3:30 AM
C
great thanks! It's a static list and will only change if i rebuild the site.
Jun 17, 2021, 3:39 AM
S
user R
cool - you won’t have any issues using that method then 👍Jun 17, 2021, 3:40 AM
C
great thanks! It's a static list and will only change if i rebuild the site.
Jun 17, 2021, 3:39 AM
A
as the internet will tell you, using index as keys in react is usually not the best idea
The only thing the key actually needs to do is to be unique, and sanity usually provides a unique key or id field for all the array points, I tend to use them as my keys
The only thing the key actually needs to do is to be unique, and sanity usually provides a unique key or id field for all the array points, I tend to use them as my keys
Jun 17, 2021, 7:09 AM
C
That's whats been bugging me. I dont seem to have a unique key or id field for my array and I dont know how to create it at the moment either
Jun 17, 2021, 7:35 AM
C
and here's my schema
{ name: 'info', title: 'Gist of product', description: 'Allows for a gist to be displayed on main product page', type: 'array', of: [ { type: 'string', }, ], },
Jun 17, 2021, 7:38 AM
J
There are some properties with an underscore prefixed such as
_id _keyon the left pane of your Graphi interface. These should be what you're looking for 👌
Jun 17, 2021, 8:36 AM
C
user V
wouldnt these be unique to the Documentitself? What happens when I have another array within my
Document?
Jun 17, 2021, 11:41 AM
J
I assume
_idwill be for each item of the array
Jun 17, 2021, 11:44 AM
C
ill give it a shot. i assumed the
_idwas for the document
Jun 17, 2021, 11:54 AM
C
thanks
Jun 17, 2021, 11:54 AM
C
ill give it a shot. i assumed the
_idwas for the document
Jun 17, 2021, 11:54 AM
J
I could be wrong 😄 give it a go anyway
Jun 17, 2021, 11:55 AM
J
I thought you wanted an unique id for each
infoitem. But looks like you want a unique id for each string element inside
info. If you know each string in the array will be unique in the list you could generate an id from that instead.
Jun 17, 2021, 12:34 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.