Render JSX inside ReactMarkDown

415 Views Asked by At

How to render JSX inside ReactMarkDown? I want to wrap my JSX elements inside ReactMarkDown component and achieve something like this,

  <ReactMarkdown>
    <Grid>
      {Some text}
    </Grid>
    <Grid>
      {Some text}
    </Grid>
 </ReactMarkdown>

What is the best possible approach for this rather than using <ReactMarkdown> multiple times inside each JSX element?

2

There are 2 best solutions below

0
On BEST ANSWER

You can take a look at MDX, it lets you use JSX and markdown together.

For example:

<Grid>
  # heading
</Grid>
<Grid>
  *italic*
</Grid>
1
On

You may want to create a custom component.

This component example map through your children node, and wrap each child with ReactMarkDown.

https://reactjs.org/docs/react-api.html#reactchildrenmap

const MarkdownPlus = ({ children }) => (        
    React.Children.map(children, child => (
       <ReactMarkdown>
              {React.cloneElement(child, {})}
       </ReactMarkdown>
    )))
);

And use it like this

 <MarkdownPlus>
    <Grid>
      {Some text}
    </Grid>
    <Grid>
      {Some text}
    </Grid>
 </MarkdownPlus>

React.Children.map vs children.map, what's the different?

Disclaimer: I'm not sure whether ReactMarkdown accepts <Grid> as child or not. If it accepts only plain text (markdown code) then the above code will not work. You will need to apply <ReactMarkDown> to each <Grid>.