When I was starting to learn how to code I never thought I could do my own Markdown Previewer. I thought it was too advanced and that it would be impossible to do it on my own. But later I learned that it is quite simple, I mean it is not simple to parse Markdown code, but we can use packages to do all the hard work for us. And only care about the styling.
And that's what we're gonna be building today, in this tutorial, I'll be using React, but it can be easily done with vanilla js.
1. Create your React project
On your terminal type the following commands:
npx create-react-app markdown-previewer
npm install --save react-markdown
The first command will generate our app, and the second command will add react-markdown to our dependencies. The react-markdown is the dependency that will parse markdown to jsx for us.
2. Planning and Creating our first components
Our App is gonna be very simple, the UI will be divided into 2 panels. The left one being the input, and the right one being the output.
So let's create them. On your src folder create both components, with MarkdownInput being a textarea and the MarkdownOutput a div tag. Inside App.js let's add markdownInput to our state, then assign it with an empty string, like so:
this.state = {
markdownInput: ''
}
Every time a user types on the form we want to update the markdown input value, to do so let's create a function that sets the state for us.
handleChange = (evt) => {
this.setState({ markdownInput: evt.target.value});
}
Now let's pass it down as a prop to the MarkdownInput component and also pass markdownInput to our MarkdownOutput component. On App.js inside the render function:
<MarkdownInput handleChange={this.handleChange} />
<MarkdownOutput source={markdownInput} />
On MarkdownInput.js, add the handleChange function:
handleChange = (evt) => {
this.props.handleChange(evt);
}
And inside the render function, add a textarea element and add a onChange event listener.
<textarea onChange={this.handleChange}></textarea>
On MarkdownOutput.js, import the ReactMarkdown component from react markdown:
import ReactMarkdown from 'react-markdown';
And inside the render function, add a div element wrapping the ReactMarkdown component. To our ReactMarkdown component render our markdown we need to pass our markdown to the source prop:
<div>
<ReactMarkdown source={this.props.source} />
</div>
And that's it! Now, all we need to do is to add our styles. Here's the link to my repository in case you want the same styles that I'm using.
Top comments (0)