How can I manually send React Synthetic Events?

I am working on adding React components to an existing project with lots of legacy code.

One problem I am facing is that React attaches handlers to delegate events to the document object. Unfortunately, for me, a lot of our legacy code intercepts click events and calls event.stopPropagation before they get into the document object (for example, to process drop-down lists and modals that close when you go beyond them).

When a click event is intercepted, the event does not extend to the React document-level event handler, and the event is not dispatched to my React components (even if the actual DOM elements for the components are located above the intercepted element in the DOM and receive the actual, non-delegated events first).

So ... question: is there a way to manually trigger a synthetic React event for a given event without hitting it. React document-level event handler? Or is there a way to move or duplicate this single event handler somewhere else?

As a backup, I am considering using jQuery to add events after mounting React components, but I would prefer not to, if possible.

+5
source share
1 answer

Depending on what you are doing, events in the reaction should generate a change in the internal state of the component or something like that (possibly changes in the global state if you use a flux-like architecture). So, with that in mind, you can create a shell, display your components, and run that shell with what you want to do.

For instance:

 function renderComponent(props={}) { ReactDOM.render(<Component {...props} />, document.getElementById('elementId')); } 

Suppose you have a button that, after clicking, should create a change in the text of the reacting component.

 $('button#my-button').on('click', function(event){ event.preventDefault(); renderComponent({text: 'Hello world!'}); }); 

So, your response component will get a text property, and there you can change the text. This is just a quick and dirty example of what you can do.

+1
source

Source: https://habr.com/ru/post/1234344/


All Articles