Reputation:
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
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
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.
renderers
option, which sounded promisingheading
was one of those (which made sense; I'd expect a renderer for every major formatting that Markdown supports)src
directory to see if the implementation was easy to findThe ability to read docs and follow trails is really important.
Upvotes: 14