File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ export * from './SelectionUtils';
33export * from './SpectrumUtils' ;
44export * from './useAsyncInterval' ;
55export * from './useCallbackWithAction' ;
6+ export * from './useChangeEventValueCallback' ;
67export * from './useCheckOverflow' ;
78export * from './useContentRect' ;
89export { default as useContextOrThrow } from './useContextOrThrow' ;
Original file line number Diff line number Diff line change 1+ import { renderHook } from '@testing-library/react-hooks' ;
2+ import { useChangeEventValueCallback } from './useChangeEventValueCallback' ;
3+
4+ beforeEach ( ( ) => {
5+ jest . clearAllMocks ( ) ;
6+ } ) ;
7+
8+ describe ( 'useChangeEventValueCallback' , ( ) => {
9+ const callback = jest . fn < void , [ string ] > ( ) ;
10+
11+ it ( 'should return a callback function' , ( ) => {
12+ const { result } = renderHook ( ( ) => useChangeEventValueCallback ( callback ) ) ;
13+ expect ( typeof result . current ) . toBe ( 'function' ) ;
14+ } ) ;
15+
16+ it ( 'should call the callback with the target value' , ( ) => {
17+ const { result } = renderHook ( ( ) => useChangeEventValueCallback ( callback ) ) ;
18+ const event = {
19+ target : { value : 'test' } ,
20+ } as React . ChangeEvent < HTMLInputElement > ;
21+
22+ result . current ( event ) ;
23+ expect ( callback ) . toHaveBeenCalledWith ( 'test' ) ;
24+ } ) ;
25+ } ) ;
Original file line number Diff line number Diff line change 1+ import { useCallback } from 'react' ;
2+
3+ /**
4+ * Returns a callback function that calls the given callback with the `target.value` of
5+ * an input change event element.
6+ * @param callback the callback to call with the `target.value`
7+ * @returns a callback function that calls the given callback with the `target.value`
8+ * @example
9+ * const [value, setValue] = useState('');
10+ * const onChange = useChangeEventValueCallback(setValue);
11+ * <input value={value} onChange={onChange} />
12+ */
13+ export function useChangeEventValueCallback < TInput extends HTMLInputElement > (
14+ callback : ( value : string ) => void
15+ ) : ( event : React . ChangeEvent < TInput > ) => void {
16+ return useCallback (
17+ ( event : React . ChangeEvent < TInput > ) => {
18+ callback ( event . target . value ) ;
19+ } ,
20+ [ callback ]
21+ ) ;
22+ }
23+
24+ export default useChangeEventValueCallback ;
You can’t perform that action at this time.
0 commit comments