2

I have a very complicated MathJax rendered equation with interactive elements inside it. This is rendered inside a react component, but, MathJax is absolutely non-compatible with react.

So I am now in the position of having a react app which renders a MathJax element with interactive elements (buttons, inputs).

Taken aside that this is a big no-no, but what is the safest way to:

  1. Update an input field value
  2. Bind a onClick action to a button

And have them become part of the state of a component?

Should I use standard js (document.querySelectorAll and addEventListener) inside the react component that update the state or is there a better way to achieve this?

Thanks for any help, input!

Please remember that short of rewriting mathJax my hands are tied in this matter.

0plus1
  • 4,475
  • 12
  • 47
  • 89
  • 1
    I think an `event bus` to onboard non-react events in to the react ecosystem (and vice-versa) might not be a bad approach too. – trk Sep 24 '18 at 05:45
  • Possible Duplicate of [How to access a DOM element in React](https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele/38093981#38093981) – Shubham Khatri Sep 24 '18 at 05:50
  • 1
    You might also want to check out [MathJax v3](https://github.com/mathjax/mathjax-v3/) (currently in beta) which no longer needs DOM access (and you could even write a custom adaptor for react's vdom). – Peter Krautzberger Sep 24 '18 at 08:39
  • Hi @PeterKrautzberger thanks for pinging this to me, I'll have a look as well! – 0plus1 Sep 25 '18 at 01:03

1 Answers1

2

Should I use standard js (document.querySelectorAll and addEventListener) inside the react component that update the state or is there a better way to achieve this?

Yes, but using refs rather than document.querySelectorAll, for at least the container, and then working within that container (via Element#querySelectorAll and such):

When to Use Refs

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

(my emphasis on the third bullet point)

Simple example from that page, slightly adjusted:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.mathJaxRef = React.createRef(); // ***
  }
  componentDidMount() {
    // Use `this.mathJaxRef.current`, which will be the `div` below, to do what
    // you need to, including hooking up event handlers if you cannot do so in the
    // usual React way
  }
  render() {
    return <div ref={this.mathJaxRef}>(MathJax stuff here)</div>;
  }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875