Help needed with creating a custom string input component in Sanity Studio
I understand the confusion here! This is a common challenge when starting with custom input components. The key thing to know is that a custom input component's onChange can only update its own field value - you can't directly patch sibling fields from within a component.
However, there's a pattern that works really well for this: instead of trying to update Field B from Field A's component, you make Field B the custom component, and have it read Field A's value and update itself accordingly.
The Right Approach
Here's how to do it using the useFormValue hook:
import { useFormValue } from 'sanity'
import { useEffect } from 'react'
import { set, unset } from 'sanity'
export function DependentStringInput(props) {
const { onChange, value } = props
// Read the value from the sibling field you want to watch
const sourceFieldValue = useFormValue(['sourceFieldName'])
// Update this field when the source field changes
useEffect(() => {
if (sourceFieldValue) {
// Derive your value from the source field
const derivedValue = `Derived from: ${sourceFieldValue}`
onChange(set(derivedValue))
} else {
onChange(unset())
}
}, [sourceFieldValue, onChange])
return (
<input
type="text"
value={value || ''}
readOnly // Make it readonly if it's purely derived
/>
)
}Then in your schema:
{
name: 'myDocument',
type: 'document',
fields: [
{
name: 'sourceFieldName',
type: 'string',
// This is the field you type in - no custom component needed
},
{
name: 'dependentFieldName',
type: 'string',
// This field watches the other one and updates itself
components: {
input: DependentStringInput
}
}
]
}Why This Works
The useFormValue hook lets you read any field value from the current document. When the source field changes, your custom component's useEffect runs and patches its own value using its own onChange prop. This is the correct way to create field dependencies in Sanity Studio.
Important Notes
useFormValue(['fieldName'])reads sibling fields at the document root level- For nested fields, use the full path:
useFormValue(['parentObject', 'nestedField']) - The
onChangeprop you receive in a custom component can only update that component's own field - this is by design for data consistency - If you need the dependent field to also be manually editable, remove the
readOnlyprop and add logic to handle user input
This pattern is much more reliable than trying to patch sibling fields directly, and it's the approach recommended in the Sanity community discussions.
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.