diff options
| author | Haishan <[email protected]> | 2020-06-07 18:15:07 +0800 |
|---|---|---|
| committer | Haishan <[email protected]> | 2020-06-07 18:41:12 +0800 |
| commit | e864feb4016739c0f5f2925257d2e7a6dc88f74d (patch) | |
| tree | 266cb906a5f17331db5ff28f6bf49ae91f8e1789 /src/components/ToggleSwitch.js | |
| parent | 201f6904c2d822d4d862ba39b8706de726eb7148 (diff) | |
fix: mode not display correctly due to clash API change
for https://github.com/haishanh/yacd/issues/491
Diffstat (limited to 'src/components/ToggleSwitch.js')
| -rw-r--r-- | src/components/ToggleSwitch.js | 76 |
1 files changed, 47 insertions, 29 deletions
diff --git a/src/components/ToggleSwitch.js b/src/components/ToggleSwitch.js index b71b49d..deca8c8 100644 --- a/src/components/ToggleSwitch.js +++ b/src/components/ToggleSwitch.js @@ -1,4 +1,4 @@ -import React, { useMemo } from 'react'; +import React, { useMemo, useCallback } from 'react'; import PropTypes from 'prop-types'; import s0 from './ToggleSwitch.module.css'; @@ -8,35 +8,53 @@ function ToggleSwitch({ options, value, name, onChange }) { () => options.map((o) => o.value).indexOf(value), [options, value] ); - const w = (100 / options.length).toPrecision(3); + + const getPortionPercentage = useCallback( + (idx) => { + 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> - <div className={s0.ToggleSwitch}> - <div - className={s0.slider} - style={{ - width: w + '%', - left: idxSelected * w + '%', - }} - /> - {options.map((o, idx) => { - const id = `${name}-${o.label}`; - const 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 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> ); } |
