Skip to content

Commit 5b76617

Browse files
committed
docs: add example on creating a mdx chart component
1 parent cc4e17d commit 5b76617

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,68 @@ See [Next.js on Netlify](https://docs.netlify.com/integrations/frameworks/next-j
255255

256256
## Frequently Asked Questions
257257

258+
### How can I add a custom MDX component?
259+
260+
Here's an example on how to create a donut chart from Chart.js (assuming you already have the dependencies installed) and use it in MDX posts. First, create a new `DonutChart.tsx` component in `components`:
261+
262+
```tsx
263+
'use client'
264+
265+
import { Doughnut } from 'react-chartjs-2'
266+
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
267+
268+
ChartJS.register(ArcElement, Tooltip, Legend)
269+
270+
const DonutChart = ({ data }) => {
271+
return <Doughnut data={data} />
272+
}
273+
274+
export default Doughnut
275+
```
276+
277+
Since the underlying `Doughnut` component uses React hooks, we add the `'use client'` directive to specify that it is a client side component. Also, there is an existing issue which prevents named components from being used, so we need to export the component as the default export.
278+
279+
Next, add the component to `MDXComponents.tsx`:
280+
281+
```diff
282+
...
283+
+ import DonutChart from './DonutChart'
284+
285+
export const components: MDXComponents = {
286+
Image,
287+
TOCInline,
288+
a: CustomLink,
289+
pre: Pre,
290+
+ DonutChart,
291+
BlogNewsletterForm,
292+
}
293+
```
294+
295+
You can now use the component in `.mdx` files:
296+
297+
```mdx
298+
## Example Donut Chart
299+
300+
export const data = {
301+
labels: ['Red', 'Blue', 'Yellow'],
302+
datasets: [
303+
{
304+
label: '# of Votes',
305+
data: [12, 19, 3],
306+
backgroundColor: [
307+
'rgba(255, 99, 132, 0.2)',
308+
'rgba(54, 162, 235, 0.2)',
309+
'rgba(255, 206, 86, 0.2)',
310+
],
311+
borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)'],
312+
borderWidth: 1,
313+
},
314+
],
315+
}
316+
317+
<DonutChart data={data} />
318+
```
319+
258320
### How can I customize the `kbar` search?
259321
260322
Add a `SearchProvider` component such as the one shown below and use it in place of the default `SearchProvider` component in `app/layout.tsx`.

0 commit comments

Comments
 (0)