Using MathLive with React

To use a mathfield with React, import the MathLive library and use a <math-field> tag.

import "./App.css";
import "//unpkg.com/mathlive";
import { useState } from "react";

function App() {
  const [value, setValue] = useState("");

  return (
    <div className="App">
      <math-field 
        onInput={evt => setValue(evt.target.value)}
      >
        {value}
      </math-field>
      <p>Value: {value}</p>
    </div>
  );
}

export default App;

Theory of Operations

A MathLive mathfield behaves as a regular DOM element:

  • define mathfields using the <math-field> tag in JSX
  • get a reference to the corresponding DOM element with the useRef() hook
  • customize the mathfield on mount with useEffect(..., []) hook

Customization

To customize a mathfield, use a useEffect hook. The last parameter is set to empty brackets to indicate the hook should only be run once when the component is mounted.

To access the mathfield DOM element use a useRef() hook. With the current property of the ref, you can access and manipulate all the properties and methods that are specific to the mathfield (value, selection, insert(), etc…). See MathfieldElement.

import "./App.css";
import "//unpkg.com/mathlive";
import { useState, useEffect, useRef } from "react";

function App() {
  // Get a ref to the mathfield element (see `ref={mf}` in the markup below)
  const mf = useRef();

  // Customize the mathfield when it is created
  useEffect(() => {
    mf.current.mathVirtualKeyboardPolicy = "manual";
    mf.current.addEventListener("focusin", (evt) => 
      window.mathVirtualKeyboard.show()
    );
    mf.current.addEventListener("focusout", (evt) => 
      window.mathVirtualKeyboard.hide()
    );
  }, []);


  const [value, setValue] = useState("");

  return (
    <div className="App">
      <math-field 
        ref={mf} 
        onInput={evt => setValue(evt.target.value)}
      >
        {value}
      </math-field>
      <p>Value: {value}</p>
    </div>
  );
}

export default App;