Skip to content

Instantly share code, notes, and snippets.

@mcleonard
Last active October 7, 2023 18:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcleonard/0433c1eca1d56489259118524824f159 to your computer and use it in GitHub Desktop.
Save mcleonard/0433c1eca1d56489259118524824f159 to your computer and use it in GitHub Desktop.
Render math expressions in Markdown with Mathjax as a React component
import ReactMarkdown from 'react-markdown';
import MathJax from 'react-mathjax';
import RemarkMathPlugin from 'remark-math';
function MarkdownRender(props) {
const newProps = {
...props,
plugins: [
RemarkMathPlugin,
],
renderers: {
...props.renderers,
math: (props) =>
<MathJax.Node formula={props.value} />,
inlineMath: (props) =>
<MathJax.Node inline formula={props.value} />
}
};
return (
<MathJax.Provider input="tex">
<ReactMarkdown {...newProps} />
</MathJax.Provider>
);
}
export default MarkdownRender
@vladtimss
Copy link

Hi! i am using typescript. I try to solve this problem - create component which can render markdown and use mathjax. I try use your logic, but new version of react-markdown doesn't have such props as renderers. So, could you please help me!

@saverioscagnoli
Copy link

saverioscagnoli commented Nov 7, 2022

This is the outdated method of doing this. Now you need:

  • react-markdown
  • remark-math
  • rehype-katex

important: you need to import "katex/dist/katex.min.css" too.

        <ReactMarkdown
          children={props.children}
          remarkPlugins={[remarkMath]}
          rehypePlugins={[rehypeKatex]}
        />

try with this

@machkouroke
Copy link

This is the outdated method of doing this. Now you need:

  • react-markdown
  • remark-math
  • rehype-katex

important: you need to import "katex/dist/katex.min.css" too.

        <ReactMarkdown
          children={props.children}
          remarkPlugins={[remarkMath]}
          rehypePlugins={[rehypeKatex]}
        />

try with this

This help me a lot thanks tou

@vladtimss
Copy link

@saverioscagnoli thank you very much!

@CNFeffery
Copy link

@saverioscagnoli after import katex/dist/katex.min.css, the webpack bundle size turn to very large😬, is there a good way to optimize?
image

@saverioscagnoli
Copy link

saverioscagnoli commented Feb 5, 2023

@CNFeffery I don't know, sorry :(
maybe limiting the fonts that get imported? I don't know if that works tho

@jelc53
Copy link

jelc53 commented Oct 7, 2023

This combination is not working for me: react-markdown, remark-math, rehype-katex. I'm running react-markdown version 8.0.7

Keep getting errors related to type of katex: "Type 'Plugin<[(KatexOptions | undefined)?]>' is not assignable to type 'Pluggable<any[]>'"

Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment