react react-hook ironman30
useToggle
A hook to toggle between true and false.
LINKS
鐵人賽連結
function useToggle(defaultState = false) {
if (typeof defaultState !== "boolean") {
throw new Error("UseToggle: defaultState should be Boolean")
}
const [state, setState] = useState(defaultState)
const toggle = useCallback(() => setState(prev => !prev), [])
return [state, toggle]
}
Params
name |
type |
description |
---|
defaultState | boolean | default as false |
Return
name |
type |
description |
---|
state | boolean | |
toggle | function | to trigger the state |
Example
function Example() {
const [isOpen, toggle] = useToggle()
return (
<>
<Button onClick={toggle}>TOGGLE</Button>
<Modal isOpen={isOpen} onClose={toggle} isCentered>
<ModalOverlay />
<ModalContent>
<ModalHeader>Hello (´・ω・`)</ModalHeader>
<ModalCloseButton />
<ModalFooter>
<Button colorScheme="blue" mr={3} onClick={toggle}>
Close
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
)
}