Building Custom Components in Sanity (Part II)

Carlos Lam

Software Engineer

2 min

Article Banner

EDIT: This article was written as of Sanity Studio v2. To see the equivalent for Sanity Studio v3, please see Building Custom Components in Sanity CMS v3 (Part II)

The previous part of this article series (Building Custom Components in Sanity CMS (Part I)) looked at using custom (React) components to visually represent complex data structures in Studio, enabling users to add and update such data. While this offers a lot of functionality, different projects will be comprised of different technologies. Due to many possible various reasons, it is perhaps possible that Sanity's Content Lake holds only a portion of a project's data, and interaction between Sanity and other database management systems is required. So far, all of the data and interactions that we have been working with are limited to the scope of what is handled within Content Lake, but this doesn't need to be a limitation.

Using the Javascript fetch API within custom components in Studio, we can establish interconnections between Content Lake and another database through APIs exposed from such database's back-end application. We may leverage these APIs in our custom components (just like in any React component), centralizing all of the project's data manipulation inside Studio as if it was an embedded Single-Page Application.

Consider an example where a school teacher may want to create a homework assignment in Studio, modelled by the schema:

1import CustomQuestions from '../constants/assignmentQuestions'
2
3export default {
4  name: 'assignment',
5  type: 'document',
6  title: 'Assignment',
7  fields: [
8    {
9      name: 'questions',
10      type: 'array',
11      title: 'Questions',
12      of: [{ ... }],
13      inputComponent: CustomQuestions
14    },
15    {
16      name: 'answers',
17      ...
18    }
19    ...
20  ]

We define a schema and declare the `questions` field to be represented by a custom component. Similar to the previous sports tournament custom component example, we create the component and define functions that handle data mutation. Suppose that student assignment submissions were held in a separate database, managed by its corresponding back-end application. By implementing and exposing APIs from the back-end application - for example, APIs that deal with marking/scoring a store submission's correctness, a possible functionality we can implement may be automatically scoring submission entries by comparing to the answers in the schema.

The result is as if we have embedded our own custom dashboard into Studio, centralizing all necessary functionality of the application in a single place.