πŸ—“οΈ Everything *[NYC] is back. A free gathering for AI builders. Sept 9 β†’

How to generate a document with code with an custom inputComponent?

5 repliesLast updated: Nov 29, 2025

Hello! i am trying to generate a document with code with an custom inputComponent, is it possible? can anyone guide me a little?
AI Update

Yes, absolutely! You can create documents programmatically from within a custom input component. Here's how to do it:

Using useClient Hook

The key is to use the useClient hook to get a Sanity client instance, then call its create() method:

import { useClient } from 'sanity'
import { set, unset } from 'sanity'

export function MyCustomInput(props) {
  const { onChange } = props
  const client = useClient({ apiVersion: '2023-01-01' })

  const handleCreateDocument = async () => {
    try {
      const newDoc = await client.create({
        _type: 'myDocumentType',
        title: 'New Document',
        // ... other fields
      })
      
      console.log('Created document:', newDoc)
      
      // Optionally update the current field value
      onChange(set(newDoc._id))
    } catch (error) {
      console.error('Error creating document:', error)
    }
  }

  return (
    <button onClick={handleCreateDocument}>
      Create New Document
    </button>
  )
}

Important Points

Setting Up the Custom Input Component

To use your custom input component, add it to your schema field definition:

{
  name: 'myField',
  type: 'string',
  components: {
    input: MyCustomInput
  }
}

Common Use Cases

The useClient hook gives you full access to the Sanity client API, so you can also update, delete, patch, or query documents as needed within your custom input component. Check out the custom input components guide for more patterns and best practices!

Show original thread
5 replies

Was this answer helpful?

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.

Related contributions