Mark Mark -4 years ago 133
React JSX Question

ReactJS & Electron - Execute Function passed by variable: string

Given a variable foo='someFunc', I'd like to be able to then call someFunc().

There is a relevant write-up about pure javascript doing exactly this here.

I can't seem to get there with React.

I'm currently doing

returnFuncFromString()
:

export default (func: string) => {
switch (func) {
case 'UpAvlToast': return toasts.UpAvlToast();
case 'UpRcvdToast': return toasts.UpRcvdToast();
default:
return null;
}
};


but after a handful of maps, this will become difficult to manage. It is being used to pass constants of message and icon variables to a toastr component. It wouldn't be surprising to have hundreds of preconfigured pairs so I'm hoping for something more dynamic.

There have been similar questions in java, and pure javascript but as there are
window
lookup issues involved in the electron bifurcation of the main and render threads they aren't terribly helpful.

Answer Source

If all of the functions are methods of the object toasts, then you should be able to use bracket notation as follows:

export default (func) => toasts[func];

The arrow function will return the value that toasts[func] evaluates to.

If there is a method on toasts that matches the variable func, this is what will be returned.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download