@wazespace/wme-react-components
Version:
A package with useful replications of the Waze Map Editor components to use in userscripts
47 lines • 1.93 kB
JavaScript
import { Component, createElement, createRef } from 'react';
import { camelToPascalCase } from './case-converters';
import { omitProps } from './object-extraction';
import { getReactDisplayName } from './react-display-name';
export function supportReactEvents(component) {
const componentWithEvents = class extends Component {
handleOnChange = this.createEventHandler('change');
handleOnClick = this.createEventHandler('click');
elementRef = createRef();
constructor(props) {
super(props);
}
createEventHandler(eventName) {
return (event) => {
const propName = `on${camelToPascalCase(eventName)}`;
if (typeof this.props[propName] === 'function') {
this.props[propName]?.(event);
}
};
}
get elementFromRef() {
return this.elementRef.current;
}
componentDidMount() {
if (!this.elementFromRef)
return;
this.elementFromRef.addEventListener('change', this.handleOnChange);
this.elementFromRef.addEventListener('click', this.handleOnClick);
}
componentWillUnmount() {
if (!this.elementFromRef)
return;
this.elementFromRef.removeEventListener('change', this.handleOnChange);
this.elementFromRef.removeEventListener('click', this.handleOnClick);
}
render() {
const nonReactiveProps = omitProps(this.props, ['onChange', 'onClick', 'children']);
return createElement(component, {
ref: this.elementRef,
...nonReactiveProps
}, this.props.children);
}
};
componentWithEvents.displayName = `WithReactEvents(${getReactDisplayName(component)})`;
return componentWithEvents;
}
//# sourceMappingURL=support-react-events.js.map