Skip to content

Commit fef559b

Browse files
authored
Merge pull request #706 from timlrx/docs/mdx-component
docs: add example on creating a mdx chart component
2 parents 27e48f5 + 5b76617 commit fef559b

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
@@ -256,6 +256,68 @@ See [Next.js on Netlify](https://docs.netlify.com/integrations/frameworks/next-j
256256

257257
## Frequently Asked Questions
258258

259+
### How can I add a custom MDX component?
260+
261+
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`:
262+
263+
```tsx
264+
'use client'
265+
266+
import { Doughnut } from 'react-chartjs-2'
267+
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
268+
269+
ChartJS.register(ArcElement, Tooltip, Legend)
270+
271+
const DonutChart = ({ data }) => {
272+
return <Doughnut data={data} />
273+
}
274+
275+
export default Doughnut
276+
```
277+
278+
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.
279+
280+
Next, add the component to `MDXComponents.tsx`:
281+
282+
```diff
283+
...
284+
+ import DonutChart from './DonutChart'
285+
286+
export const components: MDXComponents = {
287+
Image,
288+
TOCInline,
289+
a: CustomLink,
290+
pre: Pre,
291+
+ DonutChart,
292+
BlogNewsletterForm,
293+
}
294+
```
295+
296+
You can now use the component in `.mdx` files:
297+
298+
```mdx
299+
## Example Donut Chart
300+
301+
export const data = {
302+
labels: ['Red', 'Blue', 'Yellow'],
303+
datasets: [
304+
{
305+
label: '# of Votes',
306+
data: [12, 19, 3],
307+
backgroundColor: [
308+
'rgba(255, 99, 132, 0.2)',
309+
'rgba(54, 162, 235, 0.2)',
310+
'rgba(255, 206, 86, 0.2)',
311+
],
312+
borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)'],
313+
borderWidth: 1,
314+
},
315+
],
316+
}
317+
318+
<DonutChart data={data} />
319+
```
320+
259321
### How can I customize the `kbar` search?
260322
261323
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)