I am working on React web app that (amongst other things) renders out certain snippets of code that are stored in a database.
For instance, say I want to store the following code block, including indentation and newlines, in a MongoDB database and display it on the page:
<div class='parent'>
  <p class='child'>Lorem ipsum.</p>
</div>
How should I format this string of code to store it in MongoDB, and what would I need to do to render it with the same formatting on the page? I tried storing the string with \n in place of the new-lines in my MongoDB database, but that renders the text "\n" in the browser after I retrieve and display it, even if that text is wrapped in <pre> and <code> tags.
Thank you!
You can save code as a string in a MongoDB database, with \n as newlines. The trick is to use a React component that will then correctly parse the string and format it according to the rules of the language, e.g. JavaScript.
I personally use a markdown parser called Markdown-It that can use a highlighting library such as highlight.js or prism and format the code for display within pre / code tags.
Here is a condensed example of how I render a string returned from a MongoDB database and display it as code in a React component:
// CodeDisplay.js
import MarkdownIt from "markdown-it";
import hljs from "highlight.js/lib/core";
import javascript from "highlight.js/lib/languages/javascript";
hljs.registerLanguage("javascript", javascript);
export default function CodeDisplay({
  code,
  technology = "javascript"
}) {
  return (
    <div
      className="code_display"
      dangerouslySetInnerHTML={{
        __html: markdownParser.render(`\`\`\` ${technology}\n${code}\n\`\`\``)
      }}
    />
  );
}
const markdownParser = new MarkdownIt({
  breaks: true,
  highlight: function (str: string, lang = "javascript") {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${
          hljs.highlight(lang, str, true).value
        }</code></pre>`;
      } catch (error) {}
    }
    return `<pre class="hljs"><code>${markdownParser.utils.escapeHtml(
      str
    )}</code></pre>`;
  }
});
The above component will take in my code string and the language that I wish to syntax highlight, and render it out.
Here is an example of what is stored as a string in my MongoDB database:
"const Animal = (name, type) => {\n  this.name = name\n  this.type = type\n  this.age = 0\n}\n\nAnimal.prototype.birthday = function () {\n  this.age++\n}\n\nconst leo = new Animal('Leo', 'Lion')"
And here is how the CodeDisplay component will render it:

So, it's actually reasonably simple, at least when it comes to storing the code - just store it as a basic string with line breaks, and then parse it / highlight it and display it in a component in React.
I guess you asked this question a while ago, hope you got it sorted, and hope it helps anyone else running into this issue!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With