Render Mathematical Equations(Latex) using MathJax and React Hooks
1 min readMay 31, 2020
The simple way to render Latex in React using Mathjax is to add Mathjax Configuration in the index.html file under the Javascript script tag.
<script type="text/x-mathjax-config">MathJax.Hub.Config({tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]],displayMath:[["$$", "$$"], ["\\[","\\]"]]},showMathMenu: false,messageStyle: "none"});</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>
But the problem arises when the DOM updates, the Mathjax doesn’t render.
Mathjax provides a solution to our problem with Mathjax Hub Queue.
So, Let’s create a component file with the following code :
import React, { useEffect } from 'react';function Latex(props) { let node = React.createRef(); useEffect(() => { renderMath(); }); const renderMath = () => { window.MathJax.Hub.Queue([ "Typeset", window.MathJax.Hub, node.current ]); } return ( <div ref={node}> {props.children} </div> );}export default Latex;
Now you can wrap your whole app inside this Latex component.
So that anywhere Latex format was found it will render as a mathematical equation.
ReactDOM.render(<Latex><App/></Latex>, rootElement);
That’s it!!!