Terminal
With MDX you can render to the command line using Ink. This is a great way to log structured text for welcome screens, options, or even error messages.
How it works
Ink is a toolkit that lets you render React to the terminal, so with very little work you can also render MDX using the runtime library. This library handles MDX transpilation and evaluating the output React code. Ink then handles the resulting DOM structure and outputs a CLI string.
Install MDX runtime
In order to use MDX you’ll have to use the MDX runtime.
yarn add @mdx-js/runtime
Using components
Ink provides built in components for layout and color which you can use with the MDXProvider to customize the functionality and appearance of components.
Create a components
object and pass it to the MDXProvider.
It’s important to ensure that the MDXProvider wraps the MDX runtime
component.
import React from 'react'
import {Text, render} from 'ink'
import {MDXProvider} from '@mdx-js/react'
import MDX from '@mdx-js/runtime'
const components = {
h1: ({children}) => <Text bold>{children}</Text>,
p: ({children}) => <Text>{children}</Text>
}
render(
<MDXProvider components={components}>
<MDX>{MDXContent}</MDX>
</MDXProvider>
)
You can also provide other components to the runtime scope for additional functionality.
const components = {
Box,
Color,
Text,
h1: ({children}) => <Text bold>{children}</Text>,
p: ({children}) => <Text>{children}</Text>
}
This will allow you to write content like the following (and render it to the terminal!):
# Hello, world!
From <Color bgBlack white bold> MDX! </Color>
<Box marginTop={1}>
<Color bgCyan white bold>
I'm a cyan box!
</Color>
</Box>
All together
import React from 'react'
import {render, Color, Box, Text} from 'ink'
import MDX from '@mdx-js/runtime'
import {MDXProvider} from '@mdx-js/react'
const MDXContent = `
# Hello, world!
From <Color bgBlack white bold> MDX! </Color>
<Box marginTop={1}>
<Color bgCyan white bold>
I'm a cyan box!
</Color>
</Box>
`
const components = {
Box,
Color,
h1: ({children}) => <Text bold>{children}</Text>,
p: ({children}) => <Text>{children}</Text>
}
render(
<MDXProvider components={components}>
<MDX>{MDXContent}</MDX>
</MDXProvider>
)