innerHTML equivalent in React? (Markdown Previewer Project)

Hi Coders!

When I try to render HTML from Marked.js’s marked(), React renders it as a string instead of as code :rofl:
HTML_React_Small

Here is the render() code I wrote for that.
render(){
    return(
      <div>
        <textarea
          value={this.state.input}
          onChange={this.handleChange}
          id="editor"
        />
        {marked(this.state.input)}
        
        </div>
    );
  }

When I did this in JS, without React, it worked as expected, because I could pass the value from marked() specifically to innerHTML.

The code without React worked
<div id='demo'></div>
<input onkeypress ='handleChange()' id='input'></input>

<script>
function handleChange(){
  var toParse = document.getElementById('input').value;
  var parsed = document.getElementById('demo');
  parsed.innerHTML = marked(toParse);
}
</script>

JS_Results

When I tried googling this, all I got were recommendations for additional libraries/parsers/plugins. I’m guessing there’s a simple solution, using only React, that I’m overlooking? :thinking:

Thanks!

Hi @guiKailu

You need to use the dangerouslySetInnerHTML attribute to render HTML directly into a tag. See here.

2 Likes