Search code examples
htmlreactjsmathreduxmathjax

MathJax not converting TeX in dynamic element React/Redux


As a disclaimer, I'm new to MathJAX and TeX syntax.

I'm having trouble trying to transform the following:

<div class='challenge__description'>
  The Ackermann function is usually defined as follows
  $$A(m, n) =
   \begin{cases}
   n+1 &amp; \mbox{if } m = 0 \\
   A(m-1, 1) &amp; \mbox{if } m &gt; 0 \mbox{ and } n = 0 \\
   A(m-1, A(m, n-1)) &amp; \mbox{if } m &gt; 0 \mbox{ and } n &gt; 0.
   \end{cases}$$
  Its arguments are never negative and it always terminates...
</div>

And I have the following before my </body> tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({ tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]} });
  MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.querySelector('.challenge__description')]);
</script>

But nothing seems to happen. Everything prints out as is without any transformations. It works fine by itself.

An important note is that I am trying to apply MathJax transforms in React/Redux. I am dynamically setting the contents of challenge__description div using dangerouslySetInnerHTML.

react-mathjax does not seem to solve this problem as it wraps the TeX representation in a React component for processing. If I'm setting everything directly with dangerouslySetInnerHTML, then the <MathJax.Node> componentization of the TeX code is meaningless as the tags take on no special meaning.


Solution

  • The answer ended up being quite simple. In the component that needs updating with MathJax, simply include the MathJax Config and Queue in the lifecycle methods:

    constructor (props) {
      super(props);
      MathJax.Hub.Config({ tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]} });
    }
    
    componentDidMount () {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.querySelector('.challenge__description')]);
    </script>
    }
    
    componentDidUpdate () {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.querySelector('.challenge__description')]);
    </script>
    }