Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Markdown in React with Typescript

Is there a way to parse Markdown in React using Typescript?

I am trying to do things like:

import * as ReactMarkdown from 'react-markdown'
// OR
import ReactMarkdown = require('react-markdown')

But Typescript can't fint module 'react-markdown' as it's not defined:

Error: TS2307: Cannot find module 'react-markdown'.

How can I define the module and use it as a React component?

like image 288
NiklasMH Avatar asked Sep 01 '25 22:09

NiklasMH


1 Answers

I solved my problem by using commonmark package instead. They have typings and everything needed for my environment. Here is my implementation:

import { HtmlRenderer, Parser } from 'commonmark'

export class MyComponent extends React.Component<{}, {}> {
  private post: string

  constructor () {
    super()
    let parser = new Parser()
    let renderer = new HtmlRenderer()
    this.post = renderer.render(parser.parse("**works** like a charm!"))
  }

  render () {
    return (
      <div dangerouslySetInnerHTML={ {__html: this.post} } />
    )
  }
}

Also, do not forget to add the typings for commonmark:

$ typings install --global --save dt~commonmark

Thanks to the people who tried to help!

like image 92
NiklasMH Avatar answered Sep 03 '25 13:09

NiklasMH