Created
March 7, 2022 10:53
-
-
Save albannurkollari/8fb069229ce0186e0b7782056c524f96 to your computer and use it in GitHub Desktop.
Trigger a React synthetic event programmatically in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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