-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathsegmented-buttons.tsx
47 lines (42 loc) · 1.46 KB
/
segmented-buttons.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
import React, { cloneElement, FC, ReactElement, useState } from 'react'
import classNames from 'classnames'
import { SegmentedButtonProps, SegmentedButtonsProps } from './types'
import { filterByType } from '../common/component-utils'
import SegmentedButton from './button'
const EbaySegmentedButtons: FC<SegmentedButtonsProps> = ({
size,
className,
onChange = () => {},
children,
...rest
}) => {
const buttons = filterByType(children, SegmentedButton)
const [selectedIndex, setSelectedIndex] = useState(
buttons.findIndex(button => button.props.selected) || 0
)
const handleClick = (e, index: number, value: string) => {
setSelectedIndex(index)
onChange(e, { index, value })
}
return (
<div
className={classNames('segmented-buttons', size && `segmented-buttons--${size}`, className)}
{...rest}
>
<ul>
{buttons.map((button: ReactElement, i) => {
const {
value,
...buttonRest
}: SegmentedButtonProps = button.props
return cloneElement(button, {
...buttonRest,
onClick: e => handleClick(e, i, value),
selected: i === selectedIndex
} as SegmentedButtonProps)
})}
</ul>
</div>
)
}
export default EbaySegmentedButtons