Skip to content

useEventDispatcher

Hook to dispatch an Event or a CustomEvent.

Demo

INFO

The component has:

  • A state variable.
  • An inputRef ref variable attacched to an input element contained in a form.
  • An dispatch function returned from useEventDispatcher with inputRef as element.
  • An onSubmit function to handle form onSubmit that invokes dispatch function with a CustomEvent("demo") which detail is valued with input value taken from onSubmit event.
  • A useEventListener of type demo, on element inputRef and with a listener that takes CustomEvent and invokes setState with event detail.
Loading demo…
Show source code
tsx
import { BaseSyntheticEvent, useCallback, useRef, useState } from "react"
import { useEventDispatcher, useEventListener } from "../../../.."

export const UseEventDispatcher = () => {
	const [state, setState] = useState("");
	const inputRef = useRef<HTMLInputElement>(null);
	const dispatch = useEventDispatcher(inputRef);

	const onSubmit = useCallback((e: BaseSyntheticEvent) => {
		dispatch(new CustomEvent("demo", { detail: e.target[0].value }));
		e.preventDefault();
	}, [dispatch]);

	useEventListener({
		type: "demo",
		element: inputRef,
		listener: (evt: CustomEvent) => {
			setState((evt as CustomEvent<string>).detail);
		},
	});

	return (<>
		<em>State is: </em> {state}
		<br />
		<form noValidate onSubmit={onSubmit}>
			<input type="text" ref={inputRef}/>
		</form>
	</>)

}

Types

UseEventDispatcherProps

Parameters accepted by useEventDispatcher.

The single argument is the target on which events will be dispatched. Accepts either a React RefObject<HTMLElement> or a direct Window reference. Defaults to the global window when omitted.

ts
export type UseEventDispatcherProps = RefObject<HTMLElement> | Window;

UseEventDispatcherResult

Return value of useEventDispatcher.

A stable function that dispatches the provided {@link Event} or {@link CustomEvent} on the configured target element.

ts
export type UseEventDispatcherResult = (evt: Event | CustomEvent) => void;

Released under the MIT License.