skip to Main Content

So I’m trying to display some math for a school project using react and MathJax and MathJs,
the code is the following:

const InputForm = () => {

    let latex;
    let node;
    let inicial;
//    MathJax.typesetClear();

    let parenthesis = 'keep'
    let implicit = 'hide'
    
    //'sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2'
    
    const [inputExpressionText, setInputExpressionText, ] = useState(initial);
    
    function initial(){
      node = math.parse('sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2')
      latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
      console.log('Node en estado inicial:', node)
      console.log('LaTeX en estado inicial:', latex)
      
      return 'sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2';
    }

    useEffect(() => {
      //OnInput();
    },[inputExpressionText,])

    
  
  
  

    

const OnInput = function () {
  
  console.log(inputExpressionText);
  inicial = document.getElementById("input")
  node = null;

  try {
    console.log("antes de node initial", inicial.value);
    console.log("antes de node", node);
    node = math.parse(inicial.value)
    console.log("después de node", node);
    
  }
  catch (err) {
    console.log("No entro a node = math",   )
    console.log(err.toString())
  }

  try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression dentro de funcion:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)
  console.log("inputExpressionText ", inputExpressionText)
    return (
        <table className=' table  justify-content-between  '>
          <tbody>
              <tr>
                  <th>Expression</th>
                  <td><input type="text"  onInput={(e) =>{
                          setInputExpressionText(e.target.value);
                          OnInput()
                        }} id="input" value={inputExpressionText}/></td>
              </tr>
              <tr>
                  <th>Pretty print</th>
                  <td><PrettyInput latex={latex}/></td>
              </tr>
              <tr>
                  <th>Result</th>
                  <td><Result input={node} /></td>
              </tr>
          </tbody>
        </table>
    )
}

export default InputForm

the problem is in this part

try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)

When latex variale gets the tex inside the function, the console.log('LaTeX expression inside function:', latex) confirms it, console shows the corresponding tex value.

But called again right outside the OnInput function, it shows undefined breaking the code.

I’ve tried to used the proposed example mathJs in here adapting it to a react component.

That approached worked only if added live while working with vite, but stopped working if reloaded as it says the dom it’s not loaded.

I’m really stuck

2

Answers


  1. Explanation

    This is because the const only has context within the try block. If you want this to be accessible outside the block you need to declare it before the block and set it accordingly.

    Solution

    There are two main ways to do this, either with state or let.

    Here’s an example with useState:

    //make sure to import {useState} from 'react' to use this
    //declaring the variable outside of the block will allow it to be used anywhere
    [latex, setLatex] = useState('')
    
    try {
        // export the expression to LaTeX
        setLatex(node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : '')
        console.log('LaTeX expression inside function:', latex)
    
        // display and re-render the expression
        
      }
      catch (err) {
      }
      console.log("lates en fuera del try-catch",latex)
    }
      console.log("lates xfinal",latex)
    

    Here is an example with let (this will not persist like state though, it will be dumped on every re-render)

    let latex = ''
    
    try {
        // export the expression to LaTeX
        latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
        console.log('LaTeX expression inside function:', latex)
    
        // display and re-render the expression
        
      }
      catch (err) {
      }
      console.log("lates en fuera del try-catch",latex)
    }
      console.log("lates xfinal",latex)
    

    Update (3rd option)##

    You could also do this with a function as well, such as:

    const Latex = () => {
     try {
        // export the expression to LaTeX
        return node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
        console.log('LaTeX expression inside function:', latex)
    
        // display and re-render the expression
        
      }
      catch (err) {
         return 'Error'
      }
    }
    

    then you would use it like this:

    const ExmapleComponent = () => {
      //can put latex function here or in a helper file 
      const latex = Latex()
    
      return <div> jsx here </div>
    }
    

    Note to author:
    Welcome to stackoverflow!
    🙂 happy coding and hope this helps!

    Login or Signup to reply.
  2. The problem is trying to use the result of an asynchronous call back to OnInput before it has been called – latex is still set to undefined by its declaration at the top of the InputForm function.

    The solution is to trigger processing of latex and re-rendering from within OnInput after it has been called back, not immediately after the const OnInput = ... statement has been executed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search