Last active
August 3, 2024 16:43
Syntax highlighting for react-markdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import SyntaxHighlighter from 'react-syntax-highlighter'; | |
export default class CodeBlock extends React.PureComponent { | |
static propTypes = { | |
value: PropTypes.string.isRequired, | |
language: PropTypes.string, | |
} | |
static defaultProps = { | |
language: null, | |
} | |
render() { | |
const { language, value } = this.props; | |
return ( | |
<SyntaxHighlighter language={language}> | |
{value} | |
</SyntaxHighlighter> | |
); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import ReactMarkdown from 'react-markdown'; | |
import CodeBlock from './CodeBlock'; | |
class Markdown extends React.PureComponent { | |
render() { | |
return ( | |
<Container> | |
<ReactMarkdown | |
source={value} | |
renderers={{ | |
code: CodeBlock, | |
}} | |
/> | |
</Container> | |
); | |
} | |
} | |
Markdown.propTypes = { | |
value: PropTypes.string.isRequired, | |
}; | |
export default Markdown; |
👍 Works great thanks for sharing!
Wow! This is exactly the help I needed to get my head wrapped around this. Thanks!
Thanks, works great!
Typescript/functional component version
import React from "react";
import SyntaxHighlighter from "react-syntax-highlighter";
interface CodeBlockProps {
value: string;
language?: string;
}
export const CodeBlock = ({ language, value }: CodeBlockProps) => (
<SyntaxHighlighter language={language}>{value}</SyntaxHighlighter>
);
Another Version:
Codeblock
:
import React from "react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { coy } from "react-syntax-highlighter/dist/cjs/styles/prism";
interface Props {
value: string;
language: string;
}
const CodeBlock: React.FC<Props> = (props: Props) => {
const { language, value } = props;
return (
<SyntaxHighlighter language={language} style={coy}>
{value ? value : ""}
</SyntaxHighlighter>
);
};
export default CodeBlock;
ReactMarkdown
:
<ReactMarkdown
plugins={[gfm]}
skipHtml={true}
renderers={{ code: CodeBlock }}
>
{value}
</ReactMarkdown>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
getting the following error when putting ``` (three backticks) in my markdown inputfield
javascritp accept '```' as a valid string but react markdown does not for some reason