Skip to content

Instantly share code, notes, and snippets.

@albannurkollari
Created March 7, 2022 10:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albannurkollari/8fb069229ce0186e0b7782056c524f96 to your computer and use it in GitHub Desktop.
Save albannurkollari/8fb069229ce0186e0b7782056c524f96 to your computer and use it in GitHub Desktop.
Trigger a React synthetic event programmatically in JS
export const triggerNativeEventFor = (elm, { event, ...valueObj }) => {
if (!(elm instanceof Element)) {
throw new Error(`Expected an Element but received ${elm} instead!`);
}
const [prop, value] = Object.entries(valueObj)[0] ?? [];
const desc = Object.getOwnPropertyDescriptor(elm.__proto__, prop);
desc?.set?.call(elm, value);
elm.dispatchEvent(new Event(event, { bubbles: true }));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment