From MDX to Interactive Sandboxes with remark-sandpack
Created: – Last Updated:
If you have used CodeSandbox (opens in a new tab) in the past, you might also be familiar with Sandpack (opens in a new tab). It’s a library for embedding live coding environments into your documentation. Even React’s official docs (opens in a new tab) use Sandpack!
I published a package called remark-sandpack (opens in a new tab) to make authoring examples easier. Instead of writing JSX by hand, you can use code blocks. Normally you’d author the Sandpack examples like this:
<Sandpack template="react" files={{ '/App.js': 'Code goes here', }}/>With remark-sandpack, the individual files go into code blocks:
<Sandpack template="react">
```js name=App.jsCode goes here```
</Sandpack>Visit the examples folder (opens in a new tab) to see complete setups for Node.js and Astro.
If you’ve already installed and set up Sandpack with MDX, you can skip this section.
- MDX set up in your project with support for remark plugins.
- Follow the install instructions (opens in a new tab) to integrate Sandpack into your project.
Install @lekoarts/remark-sandpack in your project:
npm install @lekoarts/remark-sandpackThen add it to your list of remark plugins. The exact details depend on your setup, but here are two examples:
import remarkSandpack from '@lekoarts/remark-sandpack'import { remark } from 'remark'import remarkMdx from 'remark-mdx'import { read } from 'to-vfile'
const file = await remark() .use(remarkMdx) .use(remarkSandpack) .process(await read('example.mdx'))
console.log(String(file))import remarkSandpack from '@lekoarts/remark-sandpack'import mdx from '@astrojs/mdx'import react from '@astrojs/react'import { defineConfig } from 'astro/config'
export default defineConfig({ integrations: [mdx(), react()], markdown: { remarkPlugins: [[remarkSandpack]], },})You can also pass a componentName option to customize which component names the remark plugin looks for. By default, it’s Sandpack. For example, if you’ve created a custom <Playground> component that wraps Sandpack, you can do this:
// Node.js .use(remarkSandpack, { componentName: ['Playground'] })
// Astro remarkPlugins: [[remarkSandpack, { componentName: ['Playground'] }]]You’re now ready to author Sandpack examples by using code blocks inside your <Sandpack> components.
As shown in the introduction, the basic usage looks like this:
<Sandpack template="react">
```js name=App.jsCode goes here```
</Sandpack>You’re required to provide a name attribute on each code block. Additionally, you can provide optional configuration (following Sandpack’s file format (opens in a new tab)):
hidden- Include the file but hide it in the file exploreractive- Make this the intially active filereadOnly- Prevent editing in the UI
File configuration example:
```js name=filename.js activeconsole.log('Hello World')```