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

35 lines
1.2 KiB
TypeScript
Raw Normal View History

import { ChangeEvent, FC, PropsWithChildren } from 'react';
import classNames from 'classnames';
2020-08-22 19:03:25 +02:00
import { identity } from 'ramda';
2022-04-03 10:10:10 +02:00
import { useDomId } from './helpers/hooks';
export type BooleanControlProps = PropsWithChildren<{
2020-08-22 19:03:25 +02:00
checked?: boolean;
onChange?: (checked: boolean, e: ChangeEvent<HTMLInputElement>) => void;
className?: string;
2020-11-28 09:34:41 +01:00
inline?: boolean;
}>;
2020-08-22 19:03:25 +02:00
interface BooleanControlWithTypeProps extends BooleanControlProps {
type: 'switch' | 'checkbox';
}
export const BooleanControl: FC<BooleanControlWithTypeProps> = (
2020-11-28 09:34:41 +01:00
{ checked = false, onChange = identity, className, children, type, inline = false },
2020-08-22 19:03:25 +02:00
) => {
2022-04-03 10:10:10 +02:00
const id = useDomId();
2020-08-22 19:03:25 +02:00
const onChecked = (e: ChangeEvent<HTMLInputElement>) => onChange(e.target.checked, e);
const typeClasses = {
2022-03-05 14:04:01 +01:00
'form-switch': type === 'switch',
'form-checkbox': type === 'checkbox',
};
2020-11-28 09:34:41 +01:00
const style = inline ? { display: 'inline-block' } : {};
return (
2022-03-05 14:04:01 +01:00
<span className={classNames('form-check', typeClasses, className)} style={style}>
<input type="checkbox" className="form-check-input" id={id} checked={checked} onChange={onChecked} />
<label className="form-check-label" htmlFor={id}>{children}</label>
</span>
);
};