How to Add Markdown to the "Sanity-Gatsby-Blog" Starter
Today was my first time playing with Sanity. I was impressed: setting up the blog took all of like, two seconds and two clicks! Their ease of use is right on brand with Gatsby and Netlify, which make up the rest of the tech stack on this project.
This is my "Hello World" post for my new blog using the sanity-gatsby-blog
starter repo as the template. If you're brand new to Sanity like I am, and you're using sanity-gatsby-blog
, you may find the documentation less than helpful when it comes to replacing the default body text input with markdown.
Step-by-Step Instructions
- Create your base monorepo, from this link
- Install the Sanity CLI.
npm install -g @sanity/cli
- Run
npm install
in the root directory of your monorepo - The directories for
web/
andstudio/
inside the monorepo have their own package configurations.cd local/path/to/your/monorepo/studio
- Run
sanity install markdown
inside thestudio/
directory - Create the markdown schema type in
studio/src/schemas/objects/markdown.js
export default {
name: 'body',
title: 'Body',
type: 'markdown',
options: {
minRows: 20
}
}
- Add the markdown schema to
studio/src/schemas/schema.js
...
import markdown from './objects/markdown';
export default createSchema({
...
types: schemaTypes.concat([
...
markdown
])
});
- In
studio/src/schemas/documents/post.js
, change
{
name: 'body',
type: 'bodyPortableText',
title: 'Body'
}
to
{
name: 'body',
type: 'markdown',
title: 'Body'
}
- In
web/
runnpm install --save react-markdown
- In
web/src/templates/blog-post.js
replace_rawBody
in the GraphQL query withbody
- In
web/src/components/blog-post.js
, addimport ReactMarkdown from 'react-markdown'
- Rename
_rawBody
tobody
since that's what we're getting from our schema now - Replace
{_rawBody && <PortableText blocks={_rawBody} />}
with
{body && <ReactMarkdown source={body} />}
Git push, rebuild, etc
Explanation
The starter comes with a pre-wired schema for the blog-post
type, designed with WISYWIG editing in mind. Markdown is a replacement of it, rather than an additional feature to it.
The @sanity/cli
tool doesn't create the actual schema for markdown. It just creates access to the tooling. I spent a while scratching my head, wondering why I couldn't just change the type
attribute in post.js
to 'markdown'
. By my understanding, it's because it had nowhere to find 'markdown'
until I added it to schema.js
Your work in the CMS allows you to submit markdown content and preview it. Behind the scenes, it will be stored as a plain string. Once it crosses the transom to your front-end, you are then responsible for transforming it into HTML content for your render.
Conclusion
My first day with Sanity would have been a lot nicer if they'd offered a pre-wired markdown template to begin with. Frustration aside, this is a beautiful, powerful, flexible product. The setup was easy and magical, but there's definitely a learning curve to customizing its features.