useEventTarget
Builds value/onChange pairs from event-like targets.
Builds value/onChange pairs from event-like targets.
Import
import { useEventTarget } from '@kamod-ch/hooks'Live demo
Basic demo
Builds value/onChange pairs from event-like targets.
Current value: typed value
import { useEventTarget } from '@kamod-ch/hooks'
export default function UseEventTargetDemo() {
const [value, actions] = useEventTarget<string>({ initialValue: 'typed value' })
return (
<div>
<input value={value} onInput={(event) => actions.onChange({ target: { value: event.currentTarget.value } })} />
<p><strong>Current value:</strong> {value}</p>
<button type="button" onClick={actions.reset}>Reset</button>
</div>
)
}
API
TypeScript signature
interface EventTarget<U> {
target: {
value: U;
};
}
export interface Options<T, U> {
initialValue?: T;
transformer?: (value: U) => T;
}
declare function useEventTarget<T, U = T>(options?: Options<T, U>): readonly [T, {
readonly onChange: (e: EventTarget<U>) => void;
readonly reset: () => void;
}];
export default useEventTarget;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.