react
Markdown with Line Breaks

Markdown parse with line breaks

After installing react-markdown, I encountered an issue where simple line breaks (\n) weren't rendering as expected, it works fine if I inserted \n in the beginning of every line in my text. But I did want to improve to a clean text whether I have text inside code or fetching a text from a CMS. Despite following both the official documentation and various suggestions from the GitHub community and none solved.

Eventually, with the help of AI, I found a straightforward solution. The trick was to explicitly convert single line breaks into double line breaks (\n\n), which Markdown interprets as a new paragraph or visible line break.

Here's the final working implementation:

import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";
 
// export default function MarkdownRender({ text }: { text: string }) { // Passing as props
export default function MarkdownRender() {
  const text = `# This is a h1 line
  Soon after there is a paragraph
 
  One more paragraph
 
  We can have a very long text 
  `;
 
  const textWithLineBreaks = text.replace(/\n\s*/g, "\n\n"); // Solution: replace \n\s in every line by double \n\n
 
  return (
    <ReactMarkdown
        // Plugins to format other markdowns features
        remarkPlugins={[remarkGfm]} 
        rehypePlugins={[rehypeRaw]}
    >
      {textWithLineBreaks}
    </ReactMarkdown>
  );
}
Last updated on