I'm using markdown-to-jsx npm package to display markdown within a ReactJS application and want to highlight codeblocks with PrismJS. So I created a custom component to override codeblocks:
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import dark from 'react-syntax-highlighter/dist/cjs/styles/prism/dark';
type RichArticleCodeBlockProps = {
language: string;
children: string;
};
export const RichArticleCodeBlock: React.FC<RichArticleCodeBlockProps> = ({ language, children }) => {
return (
<SyntaxHighlighter language={language} style={dark} wrapLines={true} showLineNumbers>
{children}
</SyntaxHighlighter>
);
};
And I override it by declaring it as an option:
import React from "react";
import MarkdownToJsx from "markdown-to-jsx";
import { RichArticleCodeBlock } from "./components/RichArticleCodeBlock";
type MarkdownProps = {
value: string;
wrapper?: typeof React.Fragment;
className?: string;
};
export const Markdown = (props: MarkdownProps) => {
const markDownToJsxOptions = {
forceBlock: true,
wrapper: props.wrapper,
overrides: {
code: RichArticleCodeBlock
}
};
return (
<div className="markdown">
<MarkdownToJsx className="rich-article" options={markDownToJsxOptions}>
{props.value}
</MarkdownToJsx>
</div>
);
};
While this is working, inline code will also get highlighted/the PrismJS styling. The markdown I use looks like this:
Simply run `npm run watch` to transpile the TS files to JS files and run `npm start` to start the Function.
## How to use it
The function looks like this:
```jsx
const handleAddData = () => {
const newData = [
...ListData,
{
id: ListData.length + 1,
building: alpha.charAt(Math.floor(Math.random() * alpha.length)),
dueDate: '12/12/12'
}
]
setListData(newData)
}
/```
So three backticks for a codeblock and single backtick for inline-code. markdown-to-jsx renders inline-code as '< code >' element and a codeblock as '< pre >' '< code >'.
But it seems like I can't find a way or any documentation about how to override a code element with a pre as its direct ancestor.
(if I only override < code > like in the example above, it will also highlight inline-code.