8

I see that it is possible to embed React components with MDX:
https://v2.docusaurus.io/docs/markdown-features/#embedding-react-components-with-mdx

However, this method works for a specific page. How can I make it work for all markdown files in the docs? I am trying to add a similar component as in the link above to change the style of some inline text. I tried to edit src/pages/index.js but it didn't work.

const HighlightGreen = (children) => (
  <span
    style={{
      backgroundColor: '#00a400', // green,
      borderRadius: '2px',
      color: '#fff',
      padding: '0.2rem',
    }}>
    {children}
  </span>
);
Onur Zobi
  • 81
  • 5

3 Answers3

0

It seems now you could "swizzle" the root component, by creating a website/src/theme/Root.js file, according to: https://docusaurus.io/docs/using-themes#wrapper-your-site-with-root

Rex Wang
  • 368
  • 2
  • 5
0

yarn swizzle @docusaurus/theme-classic MDXComponents --danger

In src/theme/MDXComponents/index.js:

import {MyComponent} from "/src/components/MyComponent";
...
const MDXComponents = {
    MyComponent,
    ...
brendangibson
  • 2,377
  • 2
  • 21
  • 36
0

However, this method works for a specific page.

In the documentation there is the example where you can create a file for component:

// src/components/Highlight.js
import React from 'react';

export default function Highlight({children, color}) {
  return (
    <span
      style={{
        backgroundColor: color,
        borderRadius: '2px',
        color: '#fff',
        padding: '0.2rem',
      }}>
      {children}
    </span>
  );
}

It can be used in any page but you should add a reference:

import Highlight from '@site/src/components/Highlight';

<Highlight color="#25c2a0">Docusaurus green</Highlight>

So, you may define component once in a file and use it.


If you mean that you want to omit import statement and use component with implicit import then only way to do it in the theme. Documentation says:

If you want to register extra tag names (like the tag above), you should consider wrapping @theme/MDXComponents, so you don't have to maintain all the existing mappings. Since the swizzle CLI doesn't allow wrapping non-component files yet, you should manually create the wrapper:

import React from 'react';
// Import the original mapper
import MDXComponents from '@theme-original/MDXComponents';
import Highlight from '@site/src/components/Highlight';

export default {
  // Re-use the default mapping
  ...MDXComponents,
  // Map the "<Highlight>" tag to our Highlight component
  // `Highlight` will receive all props that were passed to `<Highlight>` in MDX
  Highlight,
};

@brendangibson provides commands for creating theme.

Maxim Suslov
  • 4,335
  • 1
  • 35
  • 29