Creating buttons and using Sanity Plugins for a more elegant solution.

3 replies
Last updated: Sep 30, 2023
Hi everyone, Is there any way for me to create a button here?
AI Update

I'd be happy to help you create a button in Sanity Studio! Since you mentioned "here" without more context, let me cover the most common scenarios for adding buttons:

Document Actions (Most Common)

The most typical place to add a button is in the document actions area (top-right of a document). You can create a custom document action that appears as a button in the actions menu.

Here's a quick example:

1. Create your action component (actions/HelloWorldAction.js):

export function HelloWorldAction(props) { 
  return {
    label: 'Hello world',
    onHandle: () => {
      // Your button logic here
      window.alert('👋 Hello from custom action')
    }    
  } 
}

2. Register it in your sanity.config.ts:

import {defineConfig} from 'sanity'
import {HelloWorldAction} from './actions/HelloWorldAction'

export default defineConfig({
  // ... other config
  document: {
    actions: (prev) => [...prev, HelloWorldAction]
  }
})

This adds your button to the document actions dropdown menu.

Other Common Button Locations

  • Custom form fields: Use the Form Components API to add buttons within field inputs
  • Custom Studio tool: Create a custom tool with buttons in a completely custom interface
  • Structure Builder panes: Add custom views with buttons using the Structure Builder

More Advanced Example

Here's a document action that actually modifies the document:

import {useDocumentOperation} from 'sanity'

export function SetAndPublishAction(props) {
  const {patch, publish} = useDocumentOperation(props.id, props.type)

  return {
    label: 'Set Date & Publish',
    onHandle: () => {
      // Update a field
      patch.execute([{set: {publishedAt: new Date().toISOString()}}])
      // Then publish
      publish.execute()
      props.onComplete()
    }
  }
}

Could you provide more details about where you'd like the button and what it should do? That way I can give you more specific guidance!

Hey,
user T
. That can be done through Sanity Plugins . Hope that helps
Also depending on what you need it for, https://www.sanity.io/docs/studio-tools
I just used Tools to make a separate page to edit images on, so people didn't need to leave the studio to prep pictures for upload or replacement, but also weren't confined to the space of a document pane like they would be in a custom field.
Much more elegant solution for some things. Thanks
user S

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.

Was this answer helpful?