1
1
import * as React from 'react' ;
2
- import { isFunction } from '@aws-amplify/ui' ;
2
+ import { isFunction , isString } from '@aws-amplify/ui' ;
3
3
4
- import { ToggleButtonProps , ToggleButtonGroupProps } from '../types' ;
4
+ import { ToggleButtonGroupProps } from '../types' ;
5
5
6
6
type UseToggleButtonParams = Pick <
7
7
ToggleButtonGroupProps ,
@@ -13,16 +13,18 @@ export const useToggleButtonGroup = ({
13
13
value,
14
14
isExclusive = false ,
15
15
isSelectionRequired = false ,
16
- } : UseToggleButtonParams ) : ( ( value : string ) => void ) => {
16
+ } : UseToggleButtonParams ) : ( ( value : string | undefined ) => void ) => {
17
17
// Multiple selection
18
- const handleChange : ToggleButtonProps [ 'onChange' ] = React . useCallback (
18
+ const handleChange = React . useCallback <
19
+ ( buttonValue : string | undefined ) => void
20
+ > (
19
21
( buttonValue ) => {
20
22
if ( ! isFunction ( onChange ) || ! Array . isArray ( value ) ) {
21
23
return ;
22
24
}
23
25
24
- const index = value . indexOf ( buttonValue ) ;
25
- let newValue : string [ ] ;
26
+ const index = isString ( buttonValue ) ? value . indexOf ( buttonValue ) : - 1 ;
27
+ let newValue : Array < string | undefined > ;
26
28
27
29
const shouldToggleOff = index >= 0 ;
28
30
if ( shouldToggleOff ) {
@@ -42,19 +44,19 @@ export const useToggleButtonGroup = ({
42
44
) ;
43
45
44
46
// Exclusive selection
45
- const handleExclusiveChange : ToggleButtonProps [ 'onChange' ] =
46
- React . useCallback (
47
- ( buttonValue ) => {
48
- if ( ! isFunction ( onChange ) ) {
49
- return ;
50
- }
51
-
52
- onChange (
53
- value === buttonValue && ! isSelectionRequired ? null : buttonValue
54
- ) ;
55
- } ,
56
- [ onChange , value , isSelectionRequired ]
57
- ) ;
47
+ const handleExclusiveChange = React . useCallback <
48
+ ( buttonValue : string | undefined ) => void
49
+ > (
50
+ ( buttonValue ) => {
51
+ if ( ! isFunction ( onChange ) ) {
52
+ return ;
53
+ }
54
+ onChange (
55
+ value === buttonValue && ! isSelectionRequired ? undefined : buttonValue
56
+ ) ;
57
+ } ,
58
+ [ onChange , value , isSelectionRequired ]
59
+ ) ;
58
60
59
61
return isExclusive ? handleExclusiveChange : handleChange ;
60
62
} ;
0 commit comments