Search code examples
javascriptreactjsmathjax

Access MathJax.Hub with MathJax loaded dynamically as script in React


I imported MathJax dynamically in React by adapting the accepted (updated) answer from Adding script tag to React/JSX, that is:

const MathJaxScript =() => {
  const script = document.createElement('script');
  script.type = "text/javascript";
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
  script.async = true;

  var config = 'MathJax.Hub.Config({' +
                 'extensions: ["tex2jax.js","TeX/AMSmath.js","TeX/AMSsymbols.js"],' +
                 'jax: ["input/TeX","output/HTML-CSS"],' +
               'tex2jax: {inlineMath: [ ["$","$"], ["\\(","\\)"] ],displayMath: [ ["$$","$$""], ["\\[","\\]"] ],processEscapes: true}});'
               +
               'MathJax.Hub.Startup.onload();'
               ;
      document.body.appendChild(script);
    return () => {
      document.body.removeChild(script)
    }
};
export default MathJaxScript;

LaTex now displays nicely on my pages, but when I update the content, the new LaTex content is not parsed by MathJax. I would need to call MathJax.Hub.Queue(["Typeset",MathJax.Hub]); to do so. What is the best way to access MathJax.Hub using my current setup?


Solution

  • Using Peter's comment, I was able to load MathJax just using this:

    const MathJaxScript =() => {
      const script = document.createElement('script');
      script.type = "text/javascript";
      script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
      script.async = true;
    };
    export default MathJaxScript;
    

    Then after calling the script,

    window.MathJax={tex: {inlineMath: [["$", "$"], ["\\(", "\\)"]],packages: ["base", "newcommand", "configMacros"]},svg: {fontCache: "global"}};
    

    To change the configuration.

    I realized that this appears in fact the latest doc released: https://docs.mathjax.org/_/downloads/en/v3.0-latest/pdf/