Search code examples
javascriptreactjsnext.jslatexserver-side-rendering

Mathquill on NextJS 13.3.0 or any solution to dynamically show math on browser with Next


I am building a webapp that uses LaTeX writable by user in some input to dynamically show it into another div or replacing it in the same input.

I've been trying to use Mathquill with NextJS v13.3.0, and I found this npm package that solves that for React called "React-Mathquill" (https://www.npmjs.com/package/react-mathquill), but this does not work beacuse of SSR (Server Side Rendering) according to the author, and he suggest to import the package without SSR (https://github.com/viktorstrate/react-mathquill/issues/49). The thing is, I quite do not understand how to do this, I've read the documentation according to NoSSR (https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-no-ssr) but seems a bit complex to understand and make unsure on how to do it.

If someone knows how to solve this or has a different solution with another library or something to show complex math equations (even without LaTeX) compatible with Next, I would thank you for share it

Here's what I tried:

import React, { useState } from 'react'
import { addStyles, EditableMathField } from 'react-mathquill'

addStyles()

function Test() 
{
    const [latex, setLatex] = useState('\\frac{1}{\\sqrt{2}}\\cdot 2')

    return (
        <div>

          <EditableMathField
            latex={latex}
            onChange={(mathField) => {
              setLatex(mathField.latex())
            }}
          />

          <p>{latex}</p>

        </div>
      )
}

export default Test

but this error shows up:

Server Error
ReferenceError: window is not defined

Solution

  • "use client";
    import dynamic from "next/dynamic";
    
    import { useEffect } from "react";
    import { MathField } from "react-mathquill";
    
    const EditableMathField = dynamic(
      () => import("react-mathquill").then((mod) => mod.EditableMathField),
      { ssr: false }
    );
    
    const YourComponent = () => {
     
      useEffect(() => {
        import("react-mathquill").then((mq) => {
          mq.addStyles();
        });
      }, []);
    
    // ...rest of your component
    
    }
    

    You can import addStyles like this. I ran into a similar issue, Next.js also discourages the use of manual style sheet tags in components so using Head is not recommended I guess