2022-04-29 19:08:32 +01:00
|
|
|
import React, { useCallback, useRef } from "react";
|
2022-04-28 17:44:50 -07:00
|
|
|
import styles from "./Toggle.module.css";
|
|
|
|
|
import { useToggleButton } from "@react-aria/button";
|
|
|
|
|
import classNames from "classnames";
|
|
|
|
|
import { Field } from "./Input";
|
|
|
|
|
|
2022-04-29 19:08:32 +01:00
|
|
|
export function Toggle({ id, label, className, onChange, isSelected }) {
|
2022-04-28 17:44:50 -07:00
|
|
|
const buttonRef = useRef();
|
2022-04-29 19:08:32 +01:00
|
|
|
const toggle = useCallback(() => {
|
|
|
|
|
onChange(!isSelected);
|
|
|
|
|
});
|
|
|
|
|
const { buttonProps } = useToggleButton({ isSelected }, { toggle }, buttonRef);
|
2022-04-28 17:44:50 -07:00
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<Field
|
|
|
|
|
className={classNames(
|
|
|
|
|
styles.toggle,
|
2022-04-29 19:08:32 +01:00
|
|
|
{ [styles.on]: isSelected },
|
2022-04-28 17:44:50 -07:00
|
|
|
className
|
|
|
|
|
)}
|
|
|
|
|
>
|
|
|
|
|
<button
|
|
|
|
|
{...buttonProps}
|
|
|
|
|
ref={buttonRef}
|
|
|
|
|
id={id}
|
|
|
|
|
className={classNames(styles.button, {
|
2022-04-29 19:08:32 +01:00
|
|
|
[styles.isPressed]: isSelected,
|
2022-04-28 17:44:50 -07:00
|
|
|
})}
|
|
|
|
|
>
|
|
|
|
|
<div className={styles.ball} />
|
|
|
|
|
</button>
|
|
|
|
|
<label className={styles.label} htmlFor={id}>
|
|
|
|
|
{label}
|
|
|
|
|
</label>
|
|
|
|
|
</Field>
|
|
|
|
|
);
|
|
|
|
|
}
|