Rendering Markdown and LaTeX in React

Recently I’ve been spending my nights and weekends learning React by building myself a new website. I got to the point of migrating my blog from Python (using Pelican) to React. My blog posts are all written as Jupyter notebooks, then converted to HTML files and displayed.

Notebook files are really just giant JSON objects. This means I should be able to read a notebook directly into a JavaScript file and render it with a React component. Indeed, I created a Notebook component just for this purpose. I managed to render text and code (with syntax highlighting!) and images and it all looked quite nice. Example given:

I often include math expressions along with descriptive text. In notebooks, the expressions are written in LaTeX, in the middle of Markdown text, then rendered with MathJax. You’d type something like $\sigma_U \sim \mathrm{Normal}(0, \Theta_U^2)$ and it would be rendered as

There is a not obvious conflict between Markdown and LaTeX in the line above. In LaTeX, underscores are used to denote subscripts. In Markdown, text between underscores is rendered as emphasis with <em> tags. LaTeX also makes heavy use of the backslash, it’s before every command such as \sigma. Backslashes are also used in Markdown for rendering special characters such as \_ if you want to actually type an underscore instead of emphasizing some text. Conflicts abound. Markdown and MathJax fight against each other to render this text.

Given all this, my math expressions were not rendering correctly. When I was at Udacity, our engineering team tackled this same problem when trying to display math expressions in the classroom. I didn’t know all the details, but it was clear there was not a good solution. After some intense googling, I found a GitHub issue with most of the solution. It was a bit outdated however, so I had to make a few adjustments. Here is my solution to hopefully prevent future frustration. Let this be my contribution to society.

I’m using three packages to do this: react-markdown, react-mathjax, and remark-math. After installing those, this component will successfully (at least in my case) render math expressions written in LaTeX inside Markdown.

You use this just like a ReactMarkdown component,

where cell is a Markdown cell from a notebook.

Using this I can now render beautiful math expressions written in a Jupyter notebook and displayed in a React app.

If you’re running into similar problems, I hope this was helpful!

Former physicist & neuroscientist. Teaching all things AI at Udacity. Tea is life.

Former physicist & neuroscientist. Teaching all things AI at Udacity. Tea is life.