Last active
May 29, 2022 21:22
-
-
Save hrdtbs/990d67b6c74fec5990f13ec4144e079d to your computer and use it in GitHub Desktop.
Fire React.ChangeEvent
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 fireReactChangeEvent = ( | |
element: HTMLInputElement | HTMLTextAreaElement, | |
value: string | number | |
) => { | |
const nativeInputValueSetter = Object.getOwnPropertyDescriptor( | |
element.tagName.toLowerCase() === "input" | |
? HTMLInputElement.prototype | |
: HTMLTextAreaElement.prototype, | |
"value" | |
)?.set; | |
nativeInputValueSetter?.call(element, value); | |
element.dispatchEvent(new Event("change", { bubbles: true })); | |
}; |
Author
hrdtbs
commented
May 29, 2022
- 前提として、Reactのイベントはネイティブではないので、dispatchEventで発火できません。
- 通常のフォーム要素の操作でイベントが発火しないようなケースでは、この手法でもイベントは発火しません。例えば、hidden typeのinput要素に対してこのメソッドを使っても動作しません。
- React v15.5以下で動きません。
- v17.0.2で動作を確認しています。
- 自分で似たようなものを書きたい場合は、しばらくコミットされていませんがreact-trigger-changeの実装や、cypressに同じ仕組みがあるので参考にすると良いと思います。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment