Accessing document _id in custom component for querying in Sanity
Perfect! You're on the right track, but you need to use the useFormValue hook to access the document's _id. The props passed to custom input components don't include the full document object by default in Sanity Studio v3.
Here's how to fix your code:
import { useFormValue } from 'sanity'
const GuidesWithChunksInput: React.FC<GuidesWithChunksInputProps> = (props) => {
const { value } = props;
const documentId = useFormValue(['_id'])
return (
<div>
{documentId ? (
<GuidesWithChunks chunkId={documentId} />
) : (
<div>No chunk ID available</div>
)}
</div>
);
};The useFormValue hook lets you access any field value from the current document by passing a path array. To get the document ID, you pass ['_id'].
Important notes:
- Draft vs Published IDs: The
_idyou get might have adrafts.prefix if you're editing a draft document. If you need the published ID without the prefix, you can use thegetPublishedIdutility:
import { useFormValue } from 'sanity'
import { getPublishedId } from 'sanity'
const GuidesWithChunksInput: React.FC<GuidesWithChunksInputProps> = (props) => {
const documentId = useFormValue(['_id'])
const publishedId = documentId ? getPublishedId(documentId) : null
return (
<div>
{publishedId ? (
<GuidesWithChunks chunkId={publishedId} />
) : (
<div>No chunk ID available</div>
)}
</div>
);
};Accessing other fields: You can use
useFormValueto access any field in the document - just pass the field name in the array. For nested fields, use['parent', 'child', 'fieldName'].Getting the entire document: If you need the whole document object, pass an empty array:
useFormValue([]).
This is the standard approach in Studio v3 - the old props.document pattern from v2 no longer works, which is why you're not seeing the _id in your props.
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.