4

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?

3
  • Do you have react-markdown somewhere? Have you installed it using npm? Have you downloaded it? Commented Oct 23, 2016 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. Commented Oct 23, 2016 at 16:19
  • Do you know how to make a such file? Commented Oct 23, 2016 at 16:43

1 Answer 1

6

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Using dangerouslySetInnerHTML is not a secure way to render HTML, ref: reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml. Use libreary such as npmjs.com/package/html-react-parser. stackoverflow.com/a/63111085/6133559

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.