1

I am creating an Reactjs App that gets input in a text area. I want it to render the code if there is any html markup and show in another div block and bold or italic the text as it is done here in stackoverflow's text editor like or mkd.. Here is my code:

class App extends React.Component{
      constructor(props){
              super(props);
              this.state={markdown:''};
              this.handleChange=this.handleChange.bind(this);
      }
      handleChange(event){
             this.setState({markdown:event.target.value});
      }
      render(){
             return(<div className="main">
                    <textarea onChange={this.handleChange} type="text"/>
                    <div className="textShow">{this.state.markdown}</div>
                    </div>
             )
      }
}

What improvements should I make to it to render html markup and add other functionalities I have mentioned?

1
  • Do you want to render the markdown, or render the code you write in a syntax highlighting block? or both, like when you write in your text area for example : ``` **my Code is: ** console.log('hello'); ``` it will be rendered to a bold text with a syntax highlighted console.log for that use marked package with hilight.js Commented Jul 24, 2018 at 11:34

3 Answers 3

3

You can use dangerouslySetInnerHTML like in this tip: https://zhenyong.github.io/react/tips/dangerously-set-inner-html.html

class Application extends React.Component {
     constructor(props){
              super(props);
              this.state={markdown:''};
              this.handleChange=this.handleChange.bind(this);
      }
      handleChange(event){
             this.setState({markdown:event.target.value});
      }
      render(){
             return(<div className="main">
                    <textarea onChange={this.handleChange} type="text"/>
                     <div className="textShow" 
                       dangerouslySetInnerHTML={{__html: this.state.markdown}} />

                    </div>
             )
      }
}
Sign up to request clarification or add additional context in comments.

1 Comment

add <b>My text</b> inside text area
2

This tool does what you need, it can be used to display a text editor or render text from markdown or html

https://draftjs.org/

Comments

2

Insert raw HTML using dangerouslySetInnerHTML as a last resort only.

According to the docs, "This is mainly for cooperating with DOM string manipulation libraries". When you use it, you're giving up the benefit of React's DOM management.

I would use npm module html-to-react: https://www.npmjs.com/package/html-to-react

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.