As of today, the official Notion API doesn't support code snippets. If such block exists on your Notion page, the API returns it with a type of
unsupported and its contents are empty. When I was migrating my personal blog to gatsby-source-notion-api, I found two rather convenient ways to embed code.
Not sure if it will work if you use MDX, but it works perfectly with MarkdownRemark. All you need to do is to create a code snippet on CodePen or CodeSandBox and simply throw a link to the snippet onto the page.
This approach has the great benefit of having all your code snippets put together. You can reuse them in different places, you can edit them separately from the writing process, and you can share them outside your blog as well. You can also find the plugin useful in other places like embedding tweets, youtube videos, and what-not.
Plugin docs can be found here. In short - install the plugin, add it to your
gatsby-config.js, create a code snippet 1 and throw its link to the page.
If you prefer things to be right inside the page, there is a way, and it's what I personally use on my blog. You can write a code snippet in Markdown syntax and simply disallow Notion to transform it to a code block. Start a line with
``` and put a space. Notion will automatically turn it into a code block.
Cmd/Ctrl + Z to undo this transformation. Put the snippet contents below. Then put
``` on a separate line again.
To specify syntax you want to use in the snippet, you can put it right after the first
gatsby-source-notion-api will transform it preserve it as Markdown syntax, and MarkdownRemark or MDX will transform it into valid HTML.
CAVEAT: since it's a kind of a wallhack to make the current state of Notion API a bit more usable, it's should not be a way to go when they start to support code blocks properly. So, what you need to do to make it work is to indent the contents of the whole code snippet one level up. I.e. simply select the stuff between
``` and press
Tab once. This will ensure snippet contents are rendered as snippet contents, not just as separate paragraphs.
Here's an example of what it looks like as a result:
And here's what it looks like in Notion to make it work:
You probably need to sign up at CodePen or CodeSandBox to be able to use long-lasting links to your snippets. ↩
Top comments (0)