insomnia/packages/insomnia-components/components/toggle-switch.js
Opender Singh 2586ee5ad7
Bundling improvements for insomnia-components (#2297)
* Bundling improvements for insomnia-components

* Update

* Update
2020-06-17 07:46:13 +12:00

55 lines
1.2 KiB
JavaScript

// @flow
import * as React from 'react';
import Switch from 'react-switch';
import styled from 'styled-components';
type Props = {
className?: string,
checked?: boolean,
disabled?: boolean,
onChange(checked: boolean): void | Promise<void>,
};
const ThemedSwitch: React.ComponentType<{ checked: boolean }> = styled.div`
.react-switch-bg {
background: ${({ checked }) => (checked ? 'var(--color-surprise)' : 'var(--hl-xl)')} !important;
}
`;
const ToggleSwitch: React.StatelessFunctionalComponent<Props> = ({
className,
checked: checkedProp,
onChange,
disabled,
}) => {
const [checked, setChecked] = React.useState(!!checkedProp);
// If prop changes and differs from state, update state
React.useEffect(() => {
setChecked(!!checkedProp);
}, [checkedProp]);
const callback = React.useCallback(
c => {
setChecked(c);
onChange(c);
},
[onChange],
);
return (
<ThemedSwitch checked={checked}>
<Switch
className={className}
checked={checked}
disabled={disabled}
onChange={callback}
height={20}
width={40}
/>
</ThemedSwitch>
);
};
export default ToggleSwitch;