Help with Markdown Previewer!

import React from 'react';
import marked from 'marked';

export class Markdown extends React.Component {
    constructor(){
        super();
        this.state = {
                value: '# Sample Markdown Heading'
        }
       this.handleChange = this.handleChange.bind(this);
    }  

    getMarkup(){
        var md = marked(this.state.value);
        return {__html: md};
    }

    handleChange(e){
        this.setState({
            value: e.target.value
        })
    }

    render(){
        return (
                    <div className='row'>
        <div className="input-div col-md-6">
            <h2>Input</h2>
            <textarea onChange={this.handleChange} value={this.state.value}>
                    </textarea>
        </div>
        <div className="result-div col-md-6">
            <h2>Result</h2>
            <textarea readOnly={true} value={this.state.value}>
                    <div dangerouslySetInnerHTML={this.getMarkup}></div>
                    </textarea>
        </div>
        </div>
        );
    }
}

When I try to change the input I get the same output as the input. I imported and installed the marked library but when i use it in the getMarkup() function it doesen’t appear to work. Please help the above is my code.

Looks like you should be calling the getMarkup function rather than just referencing it.

<div dangerouslySetInnerHTML={this.getMarkup()}></div>
1 Like

I tried. it still doesen’t work…

Try logging out the contents of the Marked output:

getMarkup(){
        var md = marked(this.state.value);
        console.log(md);
        return {__html: md};
    }

I’ve done what you have said and I get this output:

<h1 id="sample-markdown-heading">Sample Markdown Heading</h1>

It seems to work but I don’tknow how to pass this input to the output’s textarea.

Let’s try not using the method and just passing an object directly:

<div dangerouslySetInnerHTML={{__html: marked(this.state.value)}}></div>

If that fails, try hard coding a string into the object

<div dangerouslySetInnerHTML={{__html: marked("This *is* a _test_")}}></div>
1 Like

I’ve done that and I get this output:

[object Object]

and also on the console I get:

Warning: Use the `defaultValue` or `value` props instead of setting children on <textarea>.

Never mind I’ve solved it I just changed the <textarea> to be a <div>and added the dangerouslySetInnerHTML. Thanks anyway !! :slight_smile:

1 Like

change to … this.getMarkup()

why have you this div wrapped in a textarea … reomove the textarea wrapping the div.
think it should work fine then … as it looks pretty similar to mine.

1 Like

Yes I’ve done that already but anyway thanks. :slight_smile: