Creating your own widget
How to create and publish your own widget for Dashboard
Widgets are Sanity plugins that implement the part part:@sanity/dashboard/widget
. If you want to add your own custom widget for a specific Sanity Studio, the easiest way to get started is to initiate an empty plugin with the CLI:
sanity init plugin
When prompted for which template to use, select "A Dashboard widget with cats". You will then be asked to give your dashboard widget a name and whether or not you want to enable it in your current project, and install its dependencies. You probably want to accept all these in order to get going.
The source code will be downloaded to the plugins
folder in your project, where you can start editing the plugin.
Gotcha
Even though you name the plugin in the init prompt, you still have to use the same name that it has in the plugin’s sanity.json
. If you initiate the cats plugin, this is "name": "part:@sanity/dashboard/widget/cats"
. This means that you have to change "cats" to whatever you want to refer to in your Dashboard configuration ({ name: 'cats' }
).
When writing your widget components, it's recommended to use the DashboardWidget
component from the Sanity Studio by importing it like so:
import { DashboardWidget } from "@sanity/dashboard";
This gives you a typical widget component structure with basic styles, and the option of presenting your content in the header, footer, or body of the widget.
If you need something more flexible you can create your own component.
Setting up the widget with the default setup will give you a basic widget that looks something like this:
<DashboardWidget
header="A cat"
footer={
<Flex direction="column" align="stretch">
<Button
flex={1}
paddingX={2}
paddingY={4}
mode="bleed"
tone="primary"
text="Get new cat"
/>
</Flex>
}
>
<figure>
<img src="https://placekitten.com/300/450" />
</figure>
</DashboardWidget>
You can study the source code of these widgets to get a sense of how you can approach fetching of documents, adding configuration, and so on: