Building a custom dashboard widget to display data within Sanity Studio using groq queries.
Great question! You're looking to build a custom dashboard widget in Sanity Studio. Here's how to get started:
Using the Example Dashboard Widget
The best approach is to use the example-dashboard-widget-document-count as your boilerplate. This is an official Sanity example that shows exactly how to run GROQ queries and display data in a dashboard widget.
Basic Setup
First, you'll need to install the dashboard plugin:
npm install @sanity/dashboardThen configure it in your sanity.config.ts (or sanity.config.js):
import {defineConfig} from 'sanity'
import {dashboardTool} from '@sanity/dashboard'
export default defineConfig({
// ... other config
plugins: [
dashboardTool({
widgets: [
// Your custom widgets go here
]
})
]
})Creating Your Custom Widget
For your use case (listing all post titles), you'd create a custom widget component. Here's a simple example structure:
import React, {useEffect, useState} from 'react'
import {Card, Stack, Text} from '@sanity/ui'
import {useClient} from 'sanity'
export function PostListWidget() {
const client = useClient({apiVersion: '2023-01-01'})
const [posts, setPosts] = useState([])
useEffect(() => {
// Your GROQ query - fetch all post titles
client.fetch('*[_type == "post"]{title}')
.then(data => setPosts(data))
}, [client])
return (
<Card padding={4}>
<Stack space={3}>
<Text size={2} weight="bold">All Posts</Text>
<ul>
{posts.map((post, index) => (
<li key={index}>{post.title}</li>
))}
</ul>
</Stack>
</Card>
)
}The key parts here are:
useClienthook: This gives you access to the Sanity client to run GROQ queries within Studio- GROQ query: Replace
*[_type == "post"]{title}with whatever query fits your needs - Sanity UI: Use these components to style your widget consistently with Studio
Important Resources
- Creating your own widget - Official documentation
- Example dashboard widget - Reference implementation showing how to use
count(*)and other GROQ queries - Documents Pane plugin - If you need to display GROQ results in a view pane instead of the dashboard
The example widget uses simple GROQ methods like count(*), but you can use any GROQ query you need for more complex data fetching and transformations.
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.