user5797064
user5797064

Reputation:

Reactjs overide markdown types with react-markdown

I am using contentful to get markdown to a react component that uses react-markdown to parse the markdown

import ReactMarkdown from 'react-markdown';

    <Markdown source={text} />

Would I like to do is to override the Renderer so instead of it rendering ## as an h2 render i can pass a custom component to override the default h2 type to my own h2 component. How can i do that and is there and examples?

Upvotes: 3

Views: 4772

Answers (2)

Shah Hassan
Shah Hassan

Reputation: 146

According to the documentation you can pass your custom components. Please see the following link. I needed to just change my headings component so I did the following.

  h1: (props) => {
  return <HeadingOne className="text-[--bg-button]" {...props} />;
},

You can pass them in ReactMarkdown Component. Please see the following examples

    <ReactMarkdown
      components={{
        h1: (props) => {
          return <HeadingOne className="text-[--bg-button]" {...props} />;
        },
      }}
        children={post}
    />

You can also change other HTML elements as well using the same logic.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160191

One of the options to <ReactMarkdown> is renderers.

One of the common renderers handles headings. If you look at the default rendering you'll see this:

heading: function Heading(props) {
    return createElement('h' + props.level, getCoreProps(props), props.children);
},

So pass in your own heading handler. Check the level inside, roughly:

function CustomHeading(props) {
  if (props.level !== 2) {
    return createElement(`h${props.level}`, getCoreProps(props), props.children);
  }
  
  return <MyCustomElement {...props} />
}
  

If you don't have access to the code that commonmark-react-renderer gives you in the context of your function (which you probably won't) then you'd also need to duplicate what createElement gives you (but it's simple).


Unrelated: I've never used <ReactMarkdown> (but will), but this took me about five minutes of research. I'm including my path to encourage others to dig into their own questions and hopefully give some insight into how such things can be researched.

  1. The react-markdown home page
  2. Scanned through the "Options" section to see if custom rendering was trivially supported
  3. Found the renderers option, which sounded promising
  4. Clicked the link provided in that option's docs
  5. Saw that heading was one of those (which made sense; I'd expect a renderer for every major formatting that Markdown supports)
  6. Opened up the src directory to see if the implementation was easy to find
  7. There was only one file, so I opened it
  8. Searched the page for "heading" and found it
  9. Cut and pasted that code here

The ability to read docs and follow trails is really important.

Upvotes: 14

Related Questions