Skip to content

Instantly share code, notes, and snippets.

@hrdtbs
Last active May 29, 2022 21:22
Show Gist options
  • Save hrdtbs/990d67b6c74fec5990f13ec4144e079d to your computer and use it in GitHub Desktop.
Save hrdtbs/990d67b6c74fec5990f13ec4144e079d to your computer and use it in GitHub Desktop.
Fire React.ChangeEvent
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 }));
};
@hrdtbs
Copy link
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