[react-markdown] ReactMarkdown Components TypeScript Error #714
-
Hi. I'm beginer of TypeScript.
import ReactMarkdown from 'react-markdown'
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {dark} from 'react-syntax-highlighter/dist/cjs/styles/prism'
const components = {
code({node, inline, className, children, ...props}) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter style={dark} language={match[1]} PreTag="div" children={String(children).replace(/\n$/, '')} {...props} />
) : (
<code className={className} {...props} />
)
}
}
..,
<ReactMarkdown children={body} components={ components } />
...
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
TypeScript is alerting you that you've implicitly typed <ReactMarkdown children={body} components={ components: {
code({node, inline, className, children, ...props}) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter style={dark} language={match[1]} PreTag="div" children={String(children).replace(/\n$/, '')} {...props} />
) : (
<code className={className} {...props} />
)
}
} } /> this allows typescript to use ReactMarkdown's types directly. The second would be to import the code component type from react markdown, and use that for prop types. import type { CodeComponent } from 'react-markdown/ast-to-react'
type CodeProps = Parameters<CodeComponent>[0]
const components = {
code({node, inline, className, children, ...props}: CodeProps) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter style={dark} language={match[1]} PreTag="div" children={String(children).replace(/\n$/, '')} {...props} />
) : (
<code className={className} {...props} />
)
}
}
// ...
<ReactMarkdown children={body} components={ components } /> |
Beta Was this translation helpful? Give feedback.
-
I had to modify both suggestions First
to
Second
to
|
Beta Was this translation helpful? Give feedback.
-
I was getting a type error implementing the marked answer's second solution, but considering it's been three years it's probably just outdated. I found a pre-defined import { CodeProps } from "react-markdown/lib/ast-to-react";
const components = {
code({node, inline, className, children, ...props}: CodeProps) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter style={dark} language={match[1]} PreTag="div" children={String(children).replace(/\n$/, '')} {...props} />
) : (
<code className={className} {...props} />
)
}
} |
Beta Was this translation helpful? Give feedback.
TypeScript is alerting you that you've implicitly typed
className
as required, but it is optional.There are two ways you could go about resolving this, both involve more explicitly typing.
The first, move components inline
this allows typescript to use ReactMarkdown's types directly.
T…