How to access enclosing document in custom input component in V3?
2 replies
Last updated: Jun 20, 2023
AI Update
You're correct! In Sanity Studio V3, the document is no longer passed as a prop to custom input components like it was in V2. The migration path is to use the useFormValue() hook instead.
Here's how to access the enclosing document in V3:
Using useFormValue Hook
import { useFormValue } from 'sanity'
const MyCustomInput = (props) => {
// Access the entire document by passing an empty array
const document = useFormValue([])
// Or access specific fields using their path
const specificField = useFormValue(['fieldName'])
const nestedField = useFormValue(['parent', 'child', 'fieldName'])
return (
<div>
<input
type="text"
value={props.value || ''}
onChange={(e) => props.onChange(e.target.value)}
/>
{/* Now you can use document values */}
<p>Document ID: {document?._id}</p>
</div>
)
}Key Differences from V2
V2 approach (deprecated):
import { withDocument } from 'part:@sanity/form-builder'
const MyCustomInput = withDocument(
React.forwardRef((props, ref) => {
const { document } = props // Document came from props
// ...
})
)V3 approach (current):
import { useFormValue } from 'sanity'
const MyCustomInput = (props) => {
const document = useFormValue([]) // Use the hook instead
// ...
}Important Notes
- Empty array
[]returns the entire document - This is the equivalent of whatprops.documentgave you in V2 - Specific paths - You can pass a path array like
['fieldName']to access just that field - Performance - Be aware that using
useFormValue([])will cause your component to re-render whenever any field in the document changes
The withDocument documentation has more details about this migration, and you can find additional examples in the Studio Excellence course on custom form components.
Show original thread2 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.