Calling JS function in React component (nxtedition)

Hi, I’m playing around with the various approaches to creating HTML templates and invoking JS functions. I’m quite liking the nxtedition create-caspar-graphics solution with its ReactJS components approach but I’m completely stumped by how to expose JS functions from within the component.

I suspect the React app hides everything so any invoke fails. Has anyone figured this one out?

Thanks for your help

Sounds like a React question to me. There should be a lot of React specific tutorials and how to’s in the wide internet. Stack Overflow is a good starting point.

Thanks Didi, already had a look on SO. As far as I can tell the nxtedition solution wraps the React app and the output doesn’t lend itself to easy modification to create the reference to the component in order to call the function.

My ‘solution’ (which is a bit of a fudge) is to use a data field to pass in the name of the function via an UPDATE rather than INVOKE and extract it during the properties change lifecycle.

Still hoping someone can tell me I’m barking up the wrong tree and there’s a really simple way!

In general you can set the function as a property on the window object from inside the component. So something along the lines of

window.myFunction = (arg) => {
   // this can now be called by invoke and still have access to your react component

Not the most organised way of doing it, and you should probably remove the function when the component is unmounted but it should work.

1 Like

Brilliant - that works thanks. set the functions up in componentDidMount and tore them down in componentWillUnmount.