-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathToggleGroup.tsx
91 lines (75 loc) · 2.35 KB
/
ToggleGroup.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import './ToggleGroup.less';
import React, {
isValidElement,
MouseEvent,
ReactElement
} from 'react';
import { CSS_PREFIX } from '../../constants';
import { ToggleButtonProps } from '../ToggleButton/ToggleButton';
export type ToggleGroupProps<T extends ToggleButtonProps = ToggleButtonProps> = {
/**
* The orientation of the children. Default is to 'vertical'.
*/
orientation?: 'vertical' | 'horizontal';
/**
* The className which should be added.
*/
className?: string;
/**
* The value fo the `value` attribute of the children to select/press
* initially. If not given, no child is set as selected.
* Note: This prop will have full control over the pressed prop on its children. Setting select/pressed on the
* children props directly will have no effect.
*/
selected?: string;
/**
* Callback function for onChange.
*/
onChange?: (evt: MouseEvent<HTMLButtonElement>, value?: string) => void;
/**
* The children of this group. Typically, a set of `ToggleButton`s.
*/
children?: ReactElement<T>[];
} & Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'>;
export const ToggleGroupContext = React.createContext<boolean>(false);
export const ToggleGroup: React.FC<ToggleGroupProps> = ({
orientation = 'vertical',
className,
selected,
onChange = () => undefined,
children,
...passThroughProps
}) => {
const internalClassName = `${CSS_PREFIX}togglegroup`;
const finalClassName = className
? `${className} ${internalClassName}`
: internalClassName;
const orientationClass = (orientation === 'vertical')
? 'vertical-toggle-group'
: 'horizontal-toggle-group';
const handleChange = (evt: MouseEvent<HTMLButtonElement>, buttonValue?: string) => {
onChange(evt, selected === buttonValue ? undefined : buttonValue);
};
return (
<div
className={`${finalClassName} ${orientationClass}`}
{...passThroughProps}
>
{
children
?.map(child => {
if (!isValidElement(child)) {
return null;
}
return React.cloneElement<ToggleButtonProps>(child, {
key: child.props.value,
onChange: handleChange,
pressed: selected === child.props.value
});
})
.filter(child => child !== null)
}
</div>
);
};
export default ToggleGroup;