summaryrefslogtreecommitdiff
path: root/src/components/ToggleSwitch.js
blob: f04407d4cfa0acd1791291ca4ce5c643c1ced4ae (plain)
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
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';

import s0 from './ToggleSwitch.module.css';

function ToggleSwitch({ options, value, name, onChange }) {
  const idxSelected = useMemo(() => options.map(o => o.value).indexOf(value), [
    options,
    value
  ]);
  const w = (100 / options.length).toPrecision(3);
  return (
    <div>
      <div className={s0.ToggleSwitch}>
        <div
          className={s0.slider}
          style={{
            width: w + '%',
            left: idxSelected * w + '%'
          }}
        />
        {options.map((o, idx) => {
          const id = `${name}-${o.label}`;
          let className = idx === 0 ? '' : 'border-left';
          return (
            <label htmlFor={id} key={id} className={className}>
              <input
                id={id}
                name={name}
                type="radio"
                value={o.value}
                checked={value === o.value}
                onChange={onChange}
              />
              <div>{o.label}</div>
            </label>
          );
        })}
      </div>
    </div>
  );
}

ToggleSwitch.propTypes = {
  options: PropTypes.array,
  value: PropTypes.string,
  name: PropTypes.string,
  onChange: PropTypes.func
};

export default React.memo(ToggleSwitch);