Reusable snippets help you maintain consistent content across your documentation by letting you write content once and reuse it in multiple places. This follows the DRY (Don’t Repeat Yourself) principle.

Creating a Snippet

All snippets must be created in the snippets directory. These files won’t be rendered as standalone pages.

Snippets are only accessible from the snippets directory. To use a snippet as a page, import it into another file and use it as a component.

Basic Snippet

  1. Create your snippet file with reusable content:
snippets/my-snippet.mdx
Hello world! This is my content I want to reuse across pages. My keyword of the
day is {word}.
  1. Use the snippet in your pages:
destination-file.mdx
import MySnippet from '/snippets/my-snippet.mdx';

<MySnippet word="bananas" />

Variables and Components

You can also create reusable variables and components:

snippets/variables.mdx
// Export variables
export const myName = 'my name';

// Export components
export const MyComponent = ({ title }) => (
  <div>
    <h1>{title}</h1>
    <p>... content ...</p>
  </div>
);

Use them in your pages:

destination-file.mdx
import { myName, MyComponent } from '/snippets/variables.mdx';

Hello, {myName}!
<MyComponent title="Custom Title" />

Client-Side Content

For client-side rendering, check for the document object:

snippets/client-component.mdx
export const ClientComponent = () => {
  if (typeof document === "undefined") {
    return null;
  }
  
  setTimeout(() => {
    const element = document.getElementById("client-component");
    if (element) {
      element.innerHTML = "Hello, client-side component!";
    }
  }, 1);

  return <div id="client-component"></div>;
}

Was this page helpful?