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.

1
  • anyone knows :( Commented Apr 1, 2020 at 16:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
Thanks for raising this Emile, I found this issue: github.com/remarkjs/remark/issues/531 which seems to refer to: github.com/landakram/remark-wiki-link. I haven't tested it yet, but this might help you now.
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: stackoverflow.com/questions/66763417/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.