Create reusable snippets to maintain consistency across pages.
One of the core principles of software development is DRY (Don’t Repeat Yourself), which applies to documentation too. If you find yourself repeating the same content in multiple places, create a custom snippet for that content. Snippets contain content that you can import into other files to reuse. You control where the snippet appears on a page. If you ever need to update the content, you only need to edit the snippet rather than every file where the snippet is used.
Snippets are any .mdx, .md, or .jsx files imported into another file. You can place snippet files anywhere in your project.When you import a snippet into another file, the snippet only appears where you import it and does not render as a standalone page. Any file in the /snippets/ folder is always a snippet even if it is not imported into another file.
Add content to your snippet file that you want to reuse.
shared/my-snippet.mdx
Hello world! This is my content I want to reuse across pages.
2
Import the snippet
Import the snippet into your destination file using either an absolute or relative path.
---title: "An example page"description: "This is an example page that imports a snippet."---import MySnippet from "/shared/my-snippet.mdx";The snippet content displays beneath this sentence.<MySnippet />
Import the snippet from your destination file and use the variable.
destination-file.mdx
---title: "An example page"description: "This is an example page that imports a snippet with variables."---import { myName, myObject } from "/shared/custom-variables.mdx";Hello, my name is {myName} and I like {myObject.fruit}.
Use variables to pass data to a snippet when you import it.
1
Add variables to your snippet
Add variables to your snippet and pass in properties when you import it. In this example, the variable is {word}.
shared/my-snippet.mdx
My keyword of the day is {word}.
2
Import with the variable
Import the snippet into your destination file with the variable. The passed property replaces the variable in the snippet definition.
destination-file.mdx
---title: "An example page"description: "This is an example page that imports a snippet with a variable."---import MySnippet from "/shared/my-snippet.mdx";<MySnippet word="bananas" />
When creating JSX snippets, use arrow function syntax (=>) rather than function declarations. The function keyword is not supported in snippets.
2
Import the snippet
Import the snippet.
destination-file.mdx
---title: "An example page"description: "This is an example page that imports a snippet with a React component."---import { MyJSXSnippet } from "/components/my-jsx-snippet.jsx";<MyJSXSnippet />