From 48a008093b93c565607b094354f5e747ca16733b Mon Sep 17 00:00:00 2001 From: David Baker Date: Fri, 29 Apr 2022 19:08:32 +0100 Subject: [PATCH] Fix toggle button toggling Just use isSelected directly rather than makking the button have its own state. Also, the isPressed from useToggleButton looks like its whether the user has the mouse button down on it or not rather than whether the toggle switch is on, which was making the state wrong. --- src/input/Toggle.jsx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/input/Toggle.jsx b/src/input/Toggle.jsx index 3f5208b9..5435982c 100644 --- a/src/input/Toggle.jsx +++ b/src/input/Toggle.jsx @@ -1,20 +1,21 @@ -import React, { useRef } from "react"; +import React, { useCallback, useRef } from "react"; import styles from "./Toggle.module.css"; import { useToggleButton } from "@react-aria/button"; -import { useToggleState } from "@react-stately/toggle"; import classNames from "classnames"; import { Field } from "./Input"; -export function Toggle({ id, label, className, ...rest }) { +export function Toggle({ id, label, className, onChange, isSelected }) { const buttonRef = useRef(); - const state = useToggleState(rest); - const { buttonProps, isPressed } = useToggleButton(rest, state, buttonRef); + const toggle = useCallback(() => { + onChange(!isSelected); + }); + const { buttonProps } = useToggleButton({ isSelected }, { toggle }, buttonRef); return ( @@ -23,7 +24,7 @@ export function Toggle({ id, label, className, ...rest }) { ref={buttonRef} id={id} className={classNames(styles.button, { - [styles.isPressed]: isPressed, + [styles.isPressed]: isSelected, })} >