From 073d910dde4107057b86668684df2fd53fde631e Mon Sep 17 00:00:00 2001 From: Lukas Prochazka Date: Thu, 28 Mar 2024 10:07:06 +0100 Subject: [PATCH] docs: share custom components in nested MDX files (#227) * Add support for custom components in downstream MDX files * Add section to content table * Update position --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/README.md b/README.md index 90e1eab..f2b482a 100644 --- a/README.md +++ b/README.md @@ -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) @@ -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) { + 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; +}> = ({ code }) => { + const Component = useMemo( + () => getMDXComponent(code, MDX_GLOBAL_CONFIG), + [code], + ); + + return ( +

{children}

}}> + +
+ ); +}; +``` + ### Known Issues #### Cloudflare Workers