Creating Interactive Markdown with MDX
Markdown is a popular format for online content due to its easy syntax. Now you can create interactive content with React components in Markdown with MDX.
In this article, I show how to use MDX with a React application to render an interactive chart with Recharts in a markdown file.
React Static
React Static is a progressive static site generator for React. It is used for our example application. Other React static site generators like Gatsby or Next.js can also be used.
The MDX loader needs to be added to React Static, which is described in the MDX documentation.
Recharts
Recharts is a React charting library based on the fantastic D3.js library. With it, you can easily create line charts, bar charts and many other types of charts. All this is easily packaged for React developers.
To use Recharts for your own application, just install it with
yarn add recharts
Example Chart
The example chart component is shown here, a normal React component:
ExampleChart.js
import React from 'react'
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from 'recharts'
const data = [
{
name: 'Page A',
uv: 4000,
pv: 2400,
amt: 2400,
},
{
name: 'Page B',
uv: 3000,
pv: 1398,
amt: 2210,
},
{
name: 'Page C',
uv: 2000,
pv: 9800,
amt: 2290,
},
{
name: 'Page D',
uv: 2780,
pv: 3908,
amt: 2000,
},
{
name: 'Page E',
uv: 1890,
pv: 4800,
amt: 2181,
},
{
name: 'Page F',
uv: 2390,
pv: 3800,
amt: 2500,
},
{
name: 'Page G',
uv: 3490,
pv: 4300,
amt: 2100,
},
]
export default () => (
<div>
<LineChart width={400} height={400} data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line
type="monotone"
dataKey="pv"
stroke="#8884d8"
activeDot={{ r: 8 }}
/>
<Line type="monotone" dataKey="uv" stroke="#82ca9d" />
</LineChart>
</div>
)
This component displays a nice line chart.
Then this ExampleCharts component can be inserted into the MDX file:
chart.mdx
# The Chart in MDX
This is some sample data from our chart:
import ExampleChart from "../components/ExampleChart.js"
<ExampleChart></ExampleChart>
Note, that you can write whole lines of JavaScript and JSX directly in the MDX file. In our example, I imported the component and displayed it.
For the React Static application, you also need to display it in a route as a component which you can import, like so:
import React from 'react'
import Chart from './chart.mdx'
export default () => (
<div>
<Chart />
</div>
)
The result is a beautiful line chart, as you can see in this screenshot:
Conclusion
Using MDX with React Static was easy and straightforward. The example React component Recharts was easily incorporated. Thus, I hope to encourage you to try out MDX yourself.
References
- React-mdx-rechart example application: https://github.com/tderflinger/react-mdx-recharts
- MDX: https://mdxjs.com
- React Static: https://react-static.js.org
- Recharts: http://recharts.org/
Published
20 Jan 2020