Chartjs-Using Chart.js with Gatsby markdown

1👍

You need to use MDX to do this. Gatsby has good documentation on how to achieve this.

Once implemented, you’ll be able to use regular React components from your markdown content, similar to:

Your content file

// content.mdx
import { Chart } from '../components/chart'

The chart is rendered inside our MDX document.

<Chart />

Consume & render your content

// index.js
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>
    )
}

Your chart component (regular React)

import React from "react"
import chartjs from "chart-js"

export default () => {
  const Chart = new chartjs(...)

  return <Chart />
}

Leave a comment