Field Note

Adding Latex Rendering to AstroJS

astrojs math latex render
Logo of the Astro website framework.
Posted on Wednesday, August the 7th 2024
1 min read

This is surprisingly easy, we basically need to add KaTeX to our AstroJS project

npm i -S katex

And then define an AstroJS component that pre-processes the passed LaTeX code with katex.renderToString with, for example, mathml output. We may then use a <Fragment> pseudo-element with set:html in order to add the LaTeX formula as MathML.

 ---
import katex from "katex"

const { expression } = Astro.props

const html = katex.renderToString(expression, {
	throwOnError: false,
	output: 'mathml'
});
 ---

<div class="katex block my-4 lg:my-6 py-2 lg:py-6 rounded-md bg-slate-800 text-center">
	<Fragment set:html={html} />
</div>

The wrapper <div> simply creates block level wrapping box around the formula. Alternatively, we could also write an inline math component by using an inline wrapper element.

The result for e.g. the following MDX

<MathBox expression="e = mc^2" />

will be rendered as follows:

e=mc2e = mc^2

Click the link below for a longer tutorial.

friedrichkurz.me

© 2025 Friedrich Kurz

Privacy Policy