1

I am using React Markdown (https://github.com/rexxars/react-markdown) to render markdown content.

I'd like to ask how to render specific shortcode that we define in the markdown.

For example, in my markdown content, I could insert this shortcode [[ table product="mask" ]]

Then the React Markdown component could pick it up, and render a custom component that I've defined before (such as <Table product="mask" />).

I've read through the documentation but could not find any. Please let me know if you have experience doing this before.

Thank you so much.

phanatuan
  • 495
  • 1
  • 5
  • 14

1 Answers1

3

You will need the remark-shortcodes plugin and define a renderers field to tell ReactMarkdown what to do with your shortcodes:

const YourComponent = (content: string) => (
      <ReactMarkdown
        source={content}
        plugins={[
          [require("remark-shortcodes"), {startBlock: "[[", endBlock: "]]", inlineMode: true }]
        ]}
        renderers={{ shortcode: Shortcode }}
      />
)

const Shortcode = (props: any) => {
  /*
  props will looks something like:
    {
      "type": "shortcode",
      "identifier": "MailchimpForm",
      "attributes": { "id": "chfk2" }
    }
  see: https://github.com/djm/remark-shortcodes
  */
  switch (props.identifier) {
    case 'table':
      return <Table .../>;
    default:
      throw new Error('unknown shortcode')
  }
};

You might or might not need the startBlock, endBlock, and the inlineMode options depending on what you are building.

Laurent
  • 1,141
  • 1
  • 12
  • 17
  • 1
    This used to be a great solution, but unfortunately it looks like `remark-shortcodes` is no longer compatible with react-markdown. I'm battling to find a similar solution using remark-directives – Emile Esterhuizen Jun 21 '21 at 10:57
  • 1
    Thanks for raising this Emile, I found this issue: https://github.com/remarkjs/remark/issues/531 which seems to refer to: https://github.com/landakram/remark-wiki-link. I haven't tested it yet, but this might help you now. – Laurent Jul 12 '21 at 12:34
  • I should have followed up on this comment, but I managed to fight my way to a solution, I wrote little about it in case you're interested: https://stackoverflow.com/questions/66763417/react-markdown-custom-component-declaration-how-can-i-declare-in-the-renderer-t/68098106#68098106 – Emile Esterhuizen Jul 19 '21 at 07:40