Blog>
Snippets

Code Highlighting in MDX with Prism React Renderer

Show how to integrate Prism React Renderer for syntax highlighting in code blocks within MDX files.
import React from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';

const CodeBlock = ({ children, className }) => {
  const language = className.replace(/language-/, '');
  return (
    <SyntaxHighlighter style={dark} language={language} children={children} />
  );
};

export default CodeBlock;
This is a React component that uses Prism React Renderer to highlight syntax. It imports the necessary modules and defines a 'CodeBlock' component that takes 'children' as the code content and 'className' to identify the language. It then renders the 'SyntaxHighlighter' with the selected style and language.
import React from 'react';
import { MDXProvider } from '@mdx-js/react';
import CodeBlock from './CodeBlock';

const components = {
  code: CodeBlock,
};

const MDXLayout = ({ children }) => (
  <MDXProvider components={components}>{children}</MDXProvider>
);

export default MDXLayout;
This script creates a custom MDX layout using MDXProvider from '@mdx-js/react'. It imports the `CodeBlock` component created earlier to replace the default `code` block rendering in MDX files. This enables syntax highlighting for code blocks within the provided MDX content.
import React from 'react';
import MDXLayout from './MDXLayout';

const MyMDXPage = () => (
  <MDXLayout>
    <h1>My MDX Content</h1>
    {/* other MDX content here */}
  </MDXLayout>
);

export default MyMDXPage;
This is a usage example of `MDXLayout`. It wraps the MDX content (e.g., a blog post or documentation) with `MDXLayout` to apply the syntax highlighting to any code block within that content.
// Example usage of CodeBlock in an MDX file

```js
const greeting = 'Hello World';
console.log(greeting);
```
This is an example of how a code block would be written in an MDX file. The language is specified after the backticks (e.g., 'js' for JavaScript). The CodeBlock component we created will automatically apply syntax highlighting to this block.
<style>
/* You can add additional styling if needed, for example, customizing the code block appearance */
pre[class*='language-'] {
  background-color: #2d2d2d;
  border-radius: 5px;
  padding: 1em;
}
</style>
This is an optional CSS style to enhance the appearance of code blocks rendered by the Prism React Renderer. It targets the 'pre' tag with any class containing 'language-' and sets background color, border-radius, and padding to style the code block.