This post is about the Markdown Previewer project on FreeCodeCamp. This is how I started the project.
The essentials
I decided to not use Redux yet, because I only need to maintain one state inside the whole app. Redux would be such an overkill.
I got to use Prism.js and marked.js library for this project. Although I had to drop Prism.js cause it's not working and it's not necessary anyway unless if I need to implement syntax highlighting in a site.
This is a React site, with almost no static element. It is styled using SASS as a preprocesser for CSS.
marked.js
marked.js
is a very simple library to use. You can include the CDN link to get started:
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.0.2/marked.min.js" integrity="sha512-hzyXu3u+VDu/7vpPjRKFp9w33Idx7pWWNazPm+aCMRu26yZXFCby1gn1JxevVv3LDwnSbyKrvLo3JNdi4Qx1ww==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
To parse pure Markdown, use the parse
method:
let textBox = document.getElementById("text");
textBox.innerHTML = marked.parse("*This is italic*");
marked.js
also offers a ton of options, and I'm going to talk about one here.
To treat line breaks in text as an actual line break, set the necessary options to true
with marked.setOptions()
:
marked.setOptions({
breaks: true,
gfm: true
});
You can also pass them as the second argument when parsing Markdown text:
let markdownText = "# This is a heading";
let mainDiv = document.getElementById("main-part");
mainDiv.innerHTML = marked.parse(markdownText,
{
breaks: true,
gfm: true
});
A big warning when using this library: you MUST implement a HTML filter before rendering them into the DOM. marked.js
don't have a supported built-in, so it is recommended to use DOMPurify or other HTML filter.
You don't want an XSS on your site, do you?
Afterwords
This project is not really that challenging, apart from visual design (and I'm bad at designs). The next challenge though would be a jump in complexity, so I need to work harder.
Anyway, have fun everyone!
Top comments (0)