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
|
import React, { useCallback, useMemo } from 'react';
import s0 from './ToggleSwitch.module.scss';
type Props = {
options?: any[];
value?: string;
name?: string;
onChange?: (...args: any[]) => any;
};
function ToggleSwitch({ options, value, name, onChange }: Props) {
const idxSelected = useMemo(() => options.map((o) => o.value).indexOf(value), [options, value]);
const getPortionPercentage = useCallback(
(idx: number) => {
const w = Math.floor(100 / options.length);
if (idx === options.length - 1) {
return 100 - options.length * w + w;
} else if (idx > -1) {
return w;
}
},
[options]
);
const sliderStyle = useMemo(() => {
return {
width: getPortionPercentage(idxSelected) + '%',
left: idxSelected * getPortionPercentage(0) + '%',
};
}, [idxSelected, getPortionPercentage]);
return (
<div className={s0.ToggleSwitch}>
<div className={s0.slider} style={sliderStyle} />
{options.map((o, idx) => {
const id = `${name}-${o.label}`;
const className = idx === 0 ? '' : 'border-left';
return (
<label
htmlFor={id}
key={id}
className={className}
style={{
width: getPortionPercentage(idx) + '%',
}}
>
<input
id={id}
name={name}
type="radio"
value={o.value}
checked={value === o.value}
onChange={onChange}
/>
<div>{o.label}</div>
</label>
);
})}
</div>
);
}
export default React.memo(ToggleSwitch);
|