Maxqueue
Maxqueue

Reputation: 2444

React create custom event

Basically all i want to be able to do is create a custom event that i can monitor in the console. For example when a user clicks search button i want to create a custom event called "start-search".

In my jsx i have following:

const searchClick = () => {
  let event = new Event("start-search");
  window.dispatchEvent(event);
};

<button id="test" onClick={searchClick}>

For some context the idea here is that i could create a custom event called "start-search" and "end-search" that someone else could write js/jquery to do custom stuff during a given event.

I would like to be able to use similar to following in dev tools console and see event fired as expected:

monitorEvents("start-search")

Upvotes: 0

Views: 490

Answers (1)

Hugo Zapata
Hugo Zapata

Reputation: 4474

You can create a custom event with const event = new Event('start-search');

then you can dispatch it at the appropriate time with window.dispatchEvent(event)

And to monitor from the console you would write (assuming you want to monitor on the window object):

monitorEvents(window, "start-search")

Source: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Upvotes: 1

Related Questions