My Awesome Blog

React Basics - making a markdown parser

Hello guys, this is a post on react basics. This is a very basic tutorial written for people who are beginner in React.

If you haven’t read making a clock with React, you should read it first, because it covers basic concepts of React.

So, below is what we will be making. (If the codepen embed doesn’t load, try refreshing the page.)

See the Pen React markdown parser by anuragasaurus (@anuragasaurus) on CodePen.

I have created a component named “TextArea” which is the main and only component. It’s state consits of inputValue and parsedValue of markdown input.

this.state={
	inputValue:"# hello, write some `markdown` here",
	parsedValue:""
}

TextArea renders a input element where we will write in markdown and a div which will display the result. handleChange function keeps the state of component and value in input field in sync.

handleChange(e) {
    this.setState({
      inputValue: e.target.value,
      parsedValue: marked(e.target.value)
    });
}

I am using a mardown parsing library marked. As input value changes, I pass the input value in marked function which is exposed by “marked” and store it in the this.state.parsedValue.

componentDidMount is a react lifecycle function which is run after component is mounted on screen.

Edit:

I searched for alternative for dangerouslySetInnerHTML but couldn’t find one. They named it dangerouslySetInnerHTML to make developer aware of the risk of XSS attack when they use it. To avoid the risk of XSS attack, we can use DOMPurify which sanitizes the html.

Posted November 7, 2016
READ THIS NEXT:

React Basics - making a clock

Hello guys, this is a post on react basics. This is a very basic tutorial written for people who are beginner in React. So, below is what we will be making. (If the codepen embed doesn’t load, try...


author Anurag AwasthiWritten by Anurag Awasthi who lives and works in India and love to learn new things. You should follow him on Twitter