Reputation: 456
once again I am trying to render markdown in NextJS/React. For some reason my code didn't work, here it is:
import ReactMarkdown from "react-markdown";
import gfm from 'remark-gfm';
const PostContent = () => {
const source = `
# Hello, world!
---
~this doesn't work.~
`
return (
<ReactMarkdown remarkPlugins={[gfm]} children={source} />
);
};
export default PostContent;
Rather than rendering markdown, it outputs the text as normal and as if it were JSON:
Can anyone tell me why this is happening and how to solve it? Thanks!
I can't provide anymore details as this is all the code.
Upvotes: 3
Views: 3411
Reputation: 11
The approach would be
Step #1 Convert markdown to HTML string
Step #2 Render HTML string in Next.js JSX
For Step #1, I went with "npm i markdown-to-jsx"
For Step #2, I followed the tailwindcss typography guide from [tailwindcss/typography][1]
The steps are as follows:
Install the plugin from npm:
npm install -D @tailwindcss/typography
Add the plugin to your tailwind.config.js file:
module.exports = {
theme: {
// ...
},
plugins: [
require('@tailwindcss/typography'), // add this line
// ...
],
}
<div className="prose">{markdownToHTML}</div>
Upvotes: 0
Reputation: 158
You need to remove the first empty line and all the spaces at the beginning of each line.
It might look weird - but that is what ReactMarkdown
expects you to do.
Your component will end up looking like this: notice the "strange" spacing inside the backticked text.
import ReactMarkdown from "react-markdown";
import gfm from 'remark-gfm';
const PostContent = () => {
const source = `
# Hello, world!
---
~this doesn't work.~
`
return (
<ReactMarkdown remarkPlugins={[gfm]} children={source} />
);
};
export default PostContent;
Upvotes: 6
Reputation: 203512
This appears to be a whitespace issue, you've too much.
This doesn't work:
const PostContent = () => {
const source = `
# Hello, world!
---
~this doesn't work.~
`
return (
<ReactMarkdown remarkPlugins={[gfm]} children={source} />
);
};
This works:
const PostContent = () => {
const source = `
# Hello, world!
---
~this doesn't work.~
`;
return <ReactMarkdown remarkPlugins={[gfm]} children={source} />;
};
Notice the "leading" whitespace per line is removed
Upvotes: 1