Home > Software engineering >  How can I convert Markdown to HTML using react-markdown, and export it as HTML code?
How can I convert Markdown to HTML using react-markdown, and export it as HTML code?

Time:08-17

I'm trying to export HTML generated from Markdown text. ReactMarkdown component here converts html but I don't know how to export it so that the user can actually see html code that they can copy.

Frist box is textarea that takes markdown. The second box renders html, and the third box shows raw html code.

# This is a header

and some **bold** text

import ReactMarkdown from 'react-markdown'


function App() {
  const [markdown, setMarkdown] =useState('')
  // `# This is a header
  // and some **bold** text`

  const handleChange = (e) => {
    setMarkdown(e.target.value)
  }

  return (
    <div className="App">
      <textarea placeholder='Enter your markdown text' className="textarea" input={markdown} onChange={(e)=>handleChange(e)} />
       <ReactMarkdown className='reactMarkdownBox'  children={markdown} />
       <div className="htmlbox">How can I export HTML here?</div>
    </div>
  );
}

export default App;

CodePudding user response:

One way to do is to add a class on react-markdown

<ReactMarkdown children={markdown} className="react-markdown-test" />

CODESANDBOX DEMO

and then get its innerHTML as

useEffect(() => {
    const el = document.querySelector('.react-markdown-test');
    if (el) {
        const mdHTML = el.innerHTML;
        setHtml(mdHTML);
    }
}, [markdown]);
  • Related