Getting Started
Let’s add an editable mathfield to a web page.
1. Load the MathLive library from a CDN with a <script>
tag.
<script defer src="//unpkg.com/mathlive"></script>
2. Add a <math-field>
tag. The content of this tag is the initial value
of the mathfield, as a LaTeX expression.
<math-field>f(x) = \sin(x+\pi)</math-field>
LaTeX is a plain text markup language for structured documents. Most LaTeX commands start with a \
, for example \sqrt
, \frac
and \sin
. Read more about the LaTeX commands available in a mathfield
Try it Out
In the code playground below, change the content inside the <math-field>
tag.
For example change it to f(x) = \frac{x}{2}
.
Note: The code playground here and in the rest of the documentation are live: when you modify the HTML or JavaScript code the output will update to reflect your changes.
Press Reset to bring back the playground to its original state.
<math-field>x=\frac{-b\pm \sqrt{b^2-4ac}}{2a}</math-field>
MathLive with React
To use MathLive in a React project, use a <math-field>
tag with JSX:
import "//unpkg.com/mathlive";
import { useState } from "react";
export View = () => {
const [value, setValue] = useState("f(x) = \\frac{x}{2}");
return (
<math-field
onInput={evt => setValue(evt.target.value)}
> {value} </math-field>
<p>Value: {value}</p>
);
}
Caution
Caution: HTML quirks mode
The HTML quirks mode is not supported.
The host page must use the strict mode by including a <!DOCTYPE html>
directive at the top of the page.
Without it, the layout of the expression inside the mathfield may be incorrect.
Caution: file://
protocol
For security reasons there are some restrictions when using the file://
protocol. This happens if you open a file in the browser from your local file
storage. You will notice the adress in the browser address bar starts with file://
.
In this situation, some functionality may not be available and some errors may be displayed in the console.
To prevent this, use a local file server.
With VSCode, the Live Server extension can be used to launch a local development server with one click.
Here’s a complete web page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>untitled</title>
<script defer src="//unpkg.com/mathlive"></script>
</head>
<body>
<math-field>x=\frac{-b\pm \sqrt{b^2-4ac}}{2a}</math-field>
</body>
</html>