3

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?

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
NiklasMH
  • 697
  • 6
  • 16
  • Do you have `react-markdown` somewhere? Have you installed it using npm? Have you downloaded it? – Nitzan Tomer Oct 23 '16 at 16:08
  • 1
    It's not an issue with the actual packages, you're just missing the declaration files so TypeScript doesn't know about the module. Sadly, there doesn't seem to be one in DefinitelyTyped, so I guess you need to create *react-markdown.d.ts* yourself. – noppa Oct 23 '16 at 16:19
  • Do you know how to make a such file? – NiklasMH Oct 23 '16 at 16:43

1 Answers1

5

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!

NiklasMH
  • 697
  • 6
  • 16
  • 1
    Using dangerouslySetInnerHTML is not a secure way to render HTML, ref: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml. Use libreary such as https://www.npmjs.com/package/html-react-parser. https://stackoverflow.com/a/63111085/6133559 – Pramod Mali Jul 27 '20 at 08:08