Reputation: 16641
In GatsbyJS, when authoring a markdown file, how can I import and display a custom React component?
I am using the official gatsby-starter-blog starter which comes with markdown support. It works great for blog posts. However, I would now like to add a custom React component into my markdown file. What do I need to do to achieve this?
Here is my attempt. No errors, but the custom component tag does not get converted into the actual React component.
post-1\index.md:
---
title: My first post
date: "2000-01-01"
description: Wouldn't it be sweet if there was a custom React component in here?
---
import CustomComponent from '../../../src/components/CustomComponent.js'
Lorem ipsum dolor.
<CustomComponent title="Test" />
Folder structure:
content
- blog
-- post-1
---- index.md
src
- components
-- CustomComponent.js
Upvotes: 1
Views: 498
Reputation: 134
Markdown doesn't support JSX. You can use MDX for this. Gatsby has extensive documentation & official plugin for supporting the feature. You can read more at: https://www.gatsbyjs.org/docs/mdx/
MDX will allow you to have MD files looking like:
import { Chart } from '../components/chart'
The chart is rendered inside our MDX document.
<Chart />
Which you can in turn use in your Gatsby app like this:
import React from "react"
import { MDXProvider } from "@mdx-js/react"
import { MDXRenderer } from "gatsby-plugin-mdx"
import mdxContent from "./your-content.mdx"
export default () => {
return (
<MDXProvider>
<MDXRenderer>{mdxContent}</MDXRenderer>
</MDXProvider>
)
}
Upvotes: 1