Displaying Math functions using Mathquill

553 Views Asked by At

I am using the code below to display math functions in the input field. However, rather than having the functions merge to create one equation like this cos(√). each equation is added to the right of the one already displayed. Example: cos() √

import React, {useState} from 'react'
import { addStyles, EditableMathField  } from 'react-mathquill'


addStyles();

function App(props) {
  const [latex, setLatex] = useState("");
  const injectMathFunction = (latexString) => {
    setLatex((latex) => latex + latexString);
  };
  return (
    <div>
      <EditableMathField
        latex={latex} // latex value for the input field
        onChange={(mathField) => {
          
          setLatex(mathField.latex());
        }}
      />
      <button onClick={() => injectMathFunction("{\\sqrt{}}")}>√</button>
      <button onClick={() => injectMathFunction("\\frac{}{}")}>/</button>

    </div>
  );
}

I assume that the problem is in this part of the code

const injectMathFunction = (latexString) => {
    setLatex((latex) => latex + latexString);
  };
1

There are 1 best solutions below

0
On

You're concatenating the two strings. You either need to parse your \cos{} string and insert the new string. You can accomplish this with substrings.

Alternatively, you can be inserting "\cos{" and "\sqrt{" then build another function that closes them for you.