Skip to content

Commit

Permalink
docs: share custom components in nested MDX files (kentcdodds#227)
Browse files Browse the repository at this point in the history
* Add support for custom components in downstream MDX files

* Add section to content table

* Update position
  • Loading branch information
ProchaLu authored Mar 28, 2024
1 parent 2552974 commit 073d910
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ the esbuild version mdx-bundler uses.
- [Accessing named exports](#accessing-named-exports)
- [Image Bundling](#image-bundling)
- [Bundling a file.](#bundling-a-file)
- [Custom Components in Downstream Files](#custom-components-in-downstream-files)
- [Known Issues](#known-issues)
- [Inspiration](#inspiration)
- [Other Solutions](#other-solutions)
Expand Down Expand Up @@ -711,6 +712,62 @@ const {code, frontmatter} = await bundleMDX({
})
```
### Custom Components in Downstream Files
To make sure custom components are accessible in downstream MDX files, you
can use the `MDXProvider` from `@mdx-js/react` to pass custom components
to your nested imports.
```
npm install --save @mdx-js/react
```
```tsx
const globals = {
'@mdx-js/react': {
varName: 'MdxJsReact',
namedExports: ['useMDXComponents'],
defaultExport: false,
},
};
const { code } = bundleMDX({
source,
globals,
mdxOptions(options: Record<string, any>) {
return {
...options,
providerImportSource: '@mdx-js/react',
};
}
});
```
From there, you send the `code` to your client, and then:
```tsx
import { MDXProvider, useMDXComponents } from '@mdx-js/react';
const MDX_GLOBAL_CONFIG = {
MdxJsReact: {
useMDXComponents,
},
};
export const MDXComponent: React.FC<{
code: string;
frontmatter: Record<string, any>;
}> = ({ code }) => {
const Component = useMemo(
() => getMDXComponent(code, MDX_GLOBAL_CONFIG),
[code],
);

return (
<MDXProvider components={{ Text: ({ children }) => <p>{children}</p> }}>
<Component />
</MDXProvider>
);
};
```
### Known Issues
#### Cloudflare Workers
Expand Down

0 comments on commit 073d910

Please sign in to comment.