summaryrefslogtreecommitdiff
path: root/src/components/ToggleSwitch.js
diff options
context:
space:
mode:
authorHaishan <[email protected]>2019-04-12 22:59:56 +0800
committerHaishan <[email protected]>2019-04-12 23:03:12 +0800
commit68a38e735945edc6878557c8f0c745f8f5f70023 (patch)
tree3c23b77c40f9c917ac1b72a4701627b7ed088487 /src/components/ToggleSwitch.js
parent732367e65c2630fed8d53d1e73d69c0c72862336 (diff)
fix(ToggleSwitch): selected option slider left offset
Diffstat (limited to 'src/components/ToggleSwitch.js')
-rw-r--r--src/components/ToggleSwitch.js16
1 files changed, 9 insertions, 7 deletions
diff --git a/src/components/ToggleSwitch.js b/src/components/ToggleSwitch.js
index 595979f..59323c4 100644
--- a/src/components/ToggleSwitch.js
+++ b/src/components/ToggleSwitch.js
@@ -1,10 +1,13 @@
-import React, { useRef } from 'react';
+import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import s0 from 'c/ToggleSwitch.module.scss';
-function ToggleSwitch2({ options, value, name, onChange }) {
- const idxRef = useRef(null);
+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>
@@ -13,11 +16,10 @@ function ToggleSwitch2({ options, value, name, onChange }) {
className={s0.slider}
style={{
width: w + '%',
- left: idxRef.current * w + '%'
+ left: idxSelected * w + '%'
}}
/>
{options.map((o, idx) => {
- if (value === o.value) idxRef.current = idx;
const id = `${name}-${o.label}`;
let className = idx === 0 ? '' : 'border-left';
return (
@@ -39,11 +41,11 @@ function ToggleSwitch2({ options, value, name, onChange }) {
);
}
-ToggleSwitch2.propTypes = {
+ToggleSwitch.propTypes = {
options: PropTypes.array,
value: PropTypes.string,
name: PropTypes.string,
onChange: PropTypes.func
};
-export default React.memo(ToggleSwitch2);
+export default React.memo(ToggleSwitch);