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:
Click the link below for a longer tutorial.