How to create a unique key for a static list in Gatsby using React and GraphQL
React requires a unique key prop when rendering lists to efficiently track which items have changed. You have a few options here:
1. Use the array index (quick fix, but not ideal)
{myArray.map((item, index) => (
<li key={index}>{item}</li>
))}This works but isn't recommended if your array might be reordered, filtered, or items added/removed, as it can cause rendering issues.
2. Add a _key field in Sanity (recommended)
If this array is coming from a Sanity document, you should add a _key field to each array item in your schema. Sanity automatically generates _key values for objects within arrays:
{
name: 'myArray',
type: 'array',
of: [{
type: 'object',
fields: [
{name: 'content', type: 'string'}
// your other fields
]
}]
}Then in your GraphQL query, make sure to include _key:
{
myArray {
_key
content
}
}And use it in your component:
{myArray.map((item) => (
<li key={item._key}>{item.content}</li>
))}3. Generate a stable key from the content If you can't modify the schema and the values are unique, you could use the content itself:
{myArray.map((item) => (
<li key={item}>{item}</li>
))}The _key approach is definitely the cleanest solution when working with Sanity, as it's designed exactly for this purpose. Every object in an array automatically gets a _key field that persists across edits, making it perfect for React keys.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.