Skip to content

Commit 073d910

Browse files
authored
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
1 parent 2552974 commit 073d910

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ the esbuild version mdx-bundler uses.
181181
- [Accessing named exports](#accessing-named-exports)
182182
- [Image Bundling](#image-bundling)
183183
- [Bundling a file.](#bundling-a-file)
184+
- [Custom Components in Downstream Files](#custom-components-in-downstream-files)
184185
- [Known Issues](#known-issues)
185186
- [Inspiration](#inspiration)
186187
- [Other Solutions](#other-solutions)
@@ -711,6 +712,62 @@ const {code, frontmatter} = await bundleMDX({
711712
})
712713
```
713714
715+
### Custom Components in Downstream Files
716+
717+
To make sure custom components are accessible in downstream MDX files, you
718+
can use the `MDXProvider` from `@mdx-js/react` to pass custom components
719+
to your nested imports.
720+
721+
```
722+
npm install --save @mdx-js/react
723+
```
724+
725+
```tsx
726+
const globals = {
727+
'@mdx-js/react': {
728+
varName: 'MdxJsReact',
729+
namedExports: ['useMDXComponents'],
730+
defaultExport: false,
731+
},
732+
};
733+
const { code } = bundleMDX({
734+
source,
735+
globals,
736+
mdxOptions(options: Record<string, any>) {
737+
return {
738+
...options,
739+
providerImportSource: '@mdx-js/react',
740+
};
741+
}
742+
});
743+
```
744+
745+
From there, you send the `code` to your client, and then:
746+
747+
```tsx
748+
import { MDXProvider, useMDXComponents } from '@mdx-js/react';
749+
const MDX_GLOBAL_CONFIG = {
750+
MdxJsReact: {
751+
useMDXComponents,
752+
},
753+
};
754+
export const MDXComponent: React.FC<{
755+
code: string;
756+
frontmatter: Record<string, any>;
757+
}> = ({ code }) => {
758+
const Component = useMemo(
759+
() => getMDXComponent(code, MDX_GLOBAL_CONFIG),
760+
[code],
761+
);
762+
763+
return (
764+
<MDXProvider components={{ Text: ({ children }) => <p>{children}</p> }}>
765+
<Component />
766+
</MDXProvider>
767+
);
768+
};
769+
```
770+
714771
### Known Issues
715772
716773
#### Cloudflare Workers

0 commit comments

Comments
 (0)