How to display document _id in Sanity Studio GUI?
Great question! There are a few ways to display the _id in your Studio GUI, depending on what you're trying to accomplish.
Option 1: Custom Input Component (Display in the form)
If you want to show the _id directly in your document's form, you can create a custom input component that reads the _id using the useFormValue hook:
import { useFormValue } from 'sanity'
import { Stack, Text, Card } from '@sanity/ui'
const DocumentIdDisplay = (props) => {
const documentId = useFormValue(['_id'])
return (
<Stack space={2}>
{props.renderDefault(props)}
<Card padding={3} radius={2} tone="transparent">
<Text size={1} muted>Document ID: {documentId || 'Not yet created'}</Text>
</Card>
</Stack>
)
}
export default {
title: 'Objednávky',
name: 'order',
type: 'document',
icon: MdFoodBank,
fields: [
{
name: 'id',
title: 'Objednávka:',
type: 'string',
readOnly: true,
components: {
input: DocumentIdDisplay
}
},
{
name: 'note',
title: 'Poznámka',
type: 'string',
},
],
}Option 2: Use initialValue to Copy _id
If you want to automatically populate your id field with the document's _id, you can use initialValue with the document context:
{
name: 'id',
title: 'Objednávka:',
type: 'string',
readOnly: true,
initialValue: (_, context) => context.documentId
}This will set the id field to match the _id when the document is first created.
Option 3: Document Badges (Show _id in the header)
You can also display the _id as a badge at the top of your document using the badges configuration in your schema:
export default {
title: 'Objednávky',
name: 'order',
type: 'document',
icon: MdFoodBank,
badges: [
{
component: (props) => {
return {
label: props.id || 'New document',
title: `Document ID: ${props.id}`,
color: 'primary'
}
}
}
],
fields: [
// your fields...
],
}The first option with the custom input component is probably the most flexible since it shows the _id directly in your form and you can style it however you like. The useFormValue(['_id']) hook is the standard way to access the document's _id within any custom component in Studio v3.
Show original thread6 replies
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.