-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathebay-switch.tsx
56 lines (48 loc) · 1.57 KB
/
ebay-switch.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
import React, { useState, useEffect, FC, ChangeEvent, ComponentProps } from 'react'
import classNames from 'classnames'
import { EbayChangeEventHandler } from '../common/event-utils/types'
type Props = Omit<ComponentProps<'input'>, 'onChange'> & {
onChange?: EbayChangeEventHandler<HTMLInputElement, { value: string | number, checked: boolean }>;
}
const isControlled = checked => typeof checked !== 'undefined'
const EbaySwitch: FC<Props> = ({
id,
value,
name,
className,
checked,
defaultChecked = false,
onChange = () => {},
...rest
}) => {
const [isChecked, setChecked] = useState(defaultChecked)
useEffect(() => {
setChecked(!!checked)
}, [checked])
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const { value: inputValue = '', checked: inputChecked = false } = e.target || {}
onChange(e, {
value: inputValue,
checked: inputChecked
})
setChecked(inputChecked)
}
return (
<span className="switch">
<input
{...rest}
className={classNames('switch__control', className)}
id={id}
role="switch"
type="checkbox"
value={value}
aria-checked={isControlled(checked) ? checked : isChecked}
checked={isControlled(checked) ? checked : isChecked}
name={name}
onChange={handleChange}
/>
<span className="switch__button" />
</span>
)
}
export default EbaySwitch