Last active
March 15, 2022 09:40
-
-
Save wookieb/e705fa0e8c8c41323b3e22edfe307c76 to your computer and use it in GitHub Desktop.
useControlledState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useControlledState} from "@react-stately/utils"; | |
export function Toggle({open, defaultOpen, onOpenChange, children, ...props}) { | |
// you don't need to manually handle open, defaultOpen and onOpenChange | |
// just forward them to hook | |
const [isOpen, setIsOpen] = useControlledState(open, defaultOpen, onOpenChange); | |
return <div {...props}> | |
<button onClick={() => { | |
// this will call `onOpenChange` on click so you don't have to do it | |
setIsOpen(!isOpen); | |
}}> | |
Toggle | |
</button> | |
{isOpen && children} | |
</div>; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Toggle defaultOpen={true} /> // uncontrolled toggle - open by default | |
<Toggle open={isOpen} onOpenChange={(isOpen) => {setIsOpen(isOpen)}} /> // controlled toggle - you need to maintain state |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment