Skip to content

Commit b6804a5

Browse files
committed
useChangeEventValueCallback hook (DH-17600)
1 parent 8be6514 commit b6804a5

3 files changed

Lines changed: 50 additions & 0 deletions

File tree

packages/react-hooks/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ export * from './SelectionUtils';
33
export * from './SpectrumUtils';
44
export * from './useAsyncInterval';
55
export * from './useCallbackWithAction';
6+
export * from './useChangeEventValueCallback';
67
export * from './useCheckOverflow';
78
export * from './useContentRect';
89
export { default as useContextOrThrow } from './useContextOrThrow';
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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;

0 commit comments

Comments
 (0)