ReactJS: Can I create my own SyntheticEvent?

javascript, reactjs

Solution

I've created a helper function to make SyntheticEvent from Event:

export const createSyntheticEvent = <T extends Element, E extends Event>(event: E): React.SyntheticEvent<T, E> => {
  let isDefaultPrevented = false;
  let isPropagationStopped = false;
  const preventDefault = () => {
    isDefaultPrevented = true;
    event.preventDefault();
  }
  const stopPropagation = () => {
    isPropagationStopped = true;
    event.stopPropagation();
  }
  return {
    nativeEvent: event,
    currentTarget: event.currentTarget as EventTarget & T,
    target: event.target as EventTarget & T,
    bubbles: event.bubbles,
    cancelable: event.cancelable,
    defaultPrevented: event.defaultPrevented,
    eventPhase: event.eventPhase,
    isTrusted: event.isTrusted,
    preventDefault,
    isDefaultPrevented: () => isDefaultPrevented,
    stopPropagation,
    isPropagationStopped: () => isPropagationStopped,
    persist: () => {},
    timeStamp: event.timeStamp,
    type: event.type,
  };
}

That's an example of how I use it. I need to fire a change event, providing new value for the target. You can use it like this:

const target = document.createElement('input');
target.value = newValue;
const event = new Event('change', { bubbles: true });
Object.defineProperty(event, 'target', { writable: false, value: target })
const syntheticEvent = createSyntheticEvent(event) as React.ChangeEvent<typeof target>;
onChange(syntheticEvent);

Saying that, please also consider "classic" way of triggering events by creating `new Event` and dispatching it to the HTML element (which you can access with `inputRef.current`, where inputRef is defined as `inputRef = useRef()` and used as `<input ref={inputRef}`).

Problem

I am using ReactJS and it's SyntheticEvent to track the event and it's target DOM node. I am creating a few mutable components and I want them to fire SyntheticEvent to track the DOM and to track the changed value using `e.target` and `e.target.value`. How can I instantiate SyntheticEvent and assign them DOM and it's target value?

Original source