Markdown is the primary format to use when writing blog posts or pages in websites built with GatsbyJS. It would be very handy if you can embed React components in Markdown to enrich the content. This post shows how to use gatsby-remark-component plugin to embed React components.

Create site

Let's create a new Gatsby site using gatsby-starter-blog starter library.

gatsby new gatsby-markdown-component https://github.com/gatsbyjs/gatsby-starter-blog

Then install two NPM libraries gatsby-remark-component and rehype-react.

yarn add gatsby-remark-component rehype-react

Update gatsby-config.js to add gatsby-remark-component plugin to gatsby-transformer-remark.

{
  resolve: `gatsby-transformer-remark`,
  options: {
    plugins: [
      `gatsby-remark-component`,
    ],
  },
}

Update template

Modify the template of blog post src/templates/blog-post.js.

  1. Change html to htmlAst in GraphQL query.
  2. Add the following code to render() function. components is the mapping from tag names to React components. ReactPlayer comes from react-player library.
const renderAst = new rehypeReact({
  createElement: React.createElement,
  components: { 
    "video-player": ReactPlayer,
  }
}).Compiler
  1. Change <section dangerouslySetInnerHTML={{ __html:post.html }} /> to the following code.
<section>{renderAst(post.htmlAst)}</section>

Use in Markdown

In the markdown, the tag video-player can be used.

A *Youtube video* is embedded.

<video-player url='https://www.youtube.com/watch?v=AcL0MeVZIxM'>
</video-player>

More content after the video.

If you want to use other components, simply add them to the mappings of components and use the tags in Markdown.

Source code

Source code is in GitHub.

Live demo

Live demo is hosted on Netlify.