How to Use LaTeX in Next.js: Complete Guide with react-latex-next (2024)

September 15, 2024 (11mo ago)

When working with Next.js, integrating LaTeX can be a bit tricky due to outdated tutorials and libraries. After thorough research, I’ve created an updated guide to help you get started with LaTeX rendering in your Next.js projects using the react-latex-next library.

Step 1: Install the Required Modules

To begin, install the necessary library by running the following command in your project directory:

pnpm i react-latex-next

This will install react-latex-next, which allows seamless LaTeX integration within your React components.

Step 2: Setting Up the Component

Create a new file called latex.tsx in the /app/components/ directory of your Next.js project. At the beginning of this file, import the required CSS for KaTeX (used for LaTeX rendering) and the Latex component from the react-latex-next library:

import 'katex/dist/katex.min.css';
import Latex from 'react-latex-next';

Step 3: Writing the LaTeX Component

Next, create a React component that renders LaTeX either inline or in block format. This component will take an equation as a string and render it using the library we just installed.

function MyLatex({ eq }: { eq: string }) {
  // Ensure the equation is wrapped with $$...$$ for block rendering
  return <Latex>{`$$${eq}$$`}</Latex>;
}

For inline LaTeX rendering, you can use a single $:

<Latex>{`$${eq}$`}</Latex>

This setup allows you to handle both inline and block LaTeX notation in your Next.js project.

Step 4: Using the MyLatex Component

Now, you can easily include the MyLatex component in your pages. To render a LaTeX equation like Einstein's famous equation, simply use the component as follows:

<MyLatex eq="E = m c^2" />

Note that the eq prop expects a string containing the LaTeX equation.

Step 5: Running the Project

Once everything is set up, start your development server:

pnpm dev

Now, when you navigate to your page, you should see the LaTeX equation rendered beautifully.


This guide simplifies the process of integrating LaTeX in a modern Next.js project. With react-latex-next, you can now easily display mathematical formulas and scientific notations without the hassle of outdated or complex setups.