shlink-web-client/src/utils/BooleanControl.tsx

37 lines
1.2 KiB
TypeScript
Raw Normal View History

import { ChangeEvent, FC, useRef } from 'react';
import classNames from 'classnames';
import { v4 as uuid } from 'uuid';
2020-08-22 20:03:25 +03:00
import { identity } from 'ramda';
2020-08-22 20:03:25 +03:00
export interface BooleanControlProps {
checked?: boolean;
onChange?: (checked: boolean, e: ChangeEvent<HTMLInputElement>) => void;
className?: string;
2020-11-28 11:34:41 +03:00
inline?: boolean;
2020-08-22 20:03:25 +03:00
}
2020-08-22 20:03:25 +03:00
interface BooleanControlWithTypeProps extends BooleanControlProps {
type: 'switch' | 'checkbox';
}
2020-08-22 20:03:25 +03:00
const BooleanControl: FC<BooleanControlWithTypeProps> = (
2020-11-28 11:34:41 +03:00
{ checked = false, onChange = identity, className, children, type, inline = false },
2020-08-22 20:03:25 +03:00
) => {
const { current: id } = useRef(uuid());
2020-08-22 20:03:25 +03:00
const onChecked = (e: ChangeEvent<HTMLInputElement>) => onChange(e.target.checked, e);
const typeClasses = {
'custom-switch': type === 'switch',
'custom-checkbox': type === 'checkbox',
};
2020-11-28 11:34:41 +03:00
const style = inline ? { display: 'inline-block' } : {};
return (
2020-11-28 11:34:41 +03:00
<span className={classNames('custom-control', typeClasses, className)} style={style}>
<input type="checkbox" className="custom-control-input" id={id} checked={checked} onChange={onChecked} />
<label className="custom-control-label" htmlFor={id}>{children}</label>
</span>
);
};
export default BooleanControl;