※This article is a repost from the Innovator Japan Engineers’ Blog.
Preparation
Setting up a build environment can be tedious, so this time we’ll use Facebook’s official tool, create-react-app.
npm install -g create-react-app
We’ll set up the environment with the app name md-editor.
create-react-app md-editor
Next, let’s install the libraries we’ll use this time.
cd ./md-editor
npm install --save marked
npm install
Finally, start the server, and the setup is complete.
npm start
Implementation
STEP1
Before starting the implementation, let’s delete unnecessary files that we won’t use this time.
App.cssApp.test.jslogo.svg
Remove the import statements for the above files in src/index.js and src/App.js.
Then, in src/App.js, clear the content inside the return statement. (You’ll get a build error because the return statement is empty, but you can ignore it for now.)
src/index.js
src/App.js
STEP2
Create a file called Markdown.js under the src directory. This file will contain the implementation of the Markdown component.
src/Markdown.js
Just a few lines of code. This is enough to make it function as a Markdown editor. It’s almost pure JavaScript. The only React-specific part is the JSX.
STEP3
Finally, import Markdown.js into App.js.
Testing
If you want to highlight source code, you can customize marked using isagalaev/highlight.js - github.
References
Repository
The source code is available at bmf-san/til/javascript/md-editor/ - github.
Thoughts
I like React because it allows coding in a way that’s close to pure JavaScript, which reduces the risk of being locked into framework-specific knowledge.
I’ve skipped most of the code explanations, but you can check out the article Modern JavaScript by @bmf_san for more details.