Reputation: 2863
I am using an npm package called react-markdown to convert a piece of markdown text into HTML code:
import React, { PureComponent } from 'react';
import ReactMarkdown from 'react-markdown';
let body = '## Some markdown text in multiple paragraphs';
class Post extends PureComponent {
render() {
<ReactMarkdown source={body} />
}
}
export default Post;
This works fine except individual paragraphs are rendered with the standard <p>
tags. In my use-case, I need them rendered as custom components, say, <MyParagraph>
. In other words, consider the following input text:
This is paragraph one.
Lorem ipsum doler sit.
This is paragraph two.
react-markdown renders the markdown as:
<p>This is paragraph one.</p>
<p>Lorem ipsum doler sit.</p>
<p>This is paragraph two.</p>
And I need it as:
<MyParagraph>This is paragraph one.</MyParagraph>
<MyParagraph>Lorem ipsum doler sit.</MyParagraph>
<MyParagraph>This is paragraph two.</MyParagraph>
Is it even possible with this module? Or should I use something else?
Upvotes: 2
Views: 5718
Reputation: 1039
I found this: https://github.com/rexxars/react-markdown/issues/218
The renderers
property is helpful to create custom component.
import ReactDOM from "react-dom";
import React, { PureComponent } from "react";
import ReactMarkdown from "react-markdown";
let body =
"## Some markdown text in multiple paragraphs\n\nAnd this is a paragraph 1\n\nAnd this is a paragraph 2\n\nAnd this is a paragraph 3";
const MyParagraph = props => (
<p>This is inside MyParagraph, and the value is {props.children}</p>
);
// see https://github.com/rexxars/react-markdown#node-types
const renderers = {
paragraph: props => <MyParagraph {...props} />
};
class Post extends PureComponent {
render() {
return <ReactMarkdown source={body} renderers={renderers} />;
}
}
export default Post;
ReactDOM.render(<Post />, document.getElementById("root"));
Here is the codesandbox of above code: https://codesandbox.io/s/awesome-surf-r05kb?fontsize=14
Upvotes: 7