Skip to main content

useToggle

Easily toggle or set a boolean state.


API​

const [state, toggleState] = useToggle(initialValue);

Options​

  • initialValue?: boolean
    • Defaults to false
    • The initial value of the boolean state

Returns​

  • state: boolean
    • The boolean state
  • toggleState: (nextValue?: any) => void
    • A function to toggle the state, or to set the state to true/false

Examples​

Show/Hide Password​

http://localhost:3000/
import { useToggle } from 'react-power-ups';

export function DemoPassword() {
const [isShowPassword, toggleShowPassword] = useToggle(true);

return (
<>
<input type={isShowPassword ? 'text' : 'password'} defaultValue="abc123" />

{/* Just toggle from previous state */}
<button onClick={toggleShowPassword}>{isShowPassword ? 'Hide' : 'Show'} Password</button>

{/* If you want to set to specific value */}
{/* <button onClick={() => toggleShowPassword(true)}>Show Password</button> */}
{/* <button onClick={() => toggleShowPassword(false)}>Hide Password</button> */}
</>
);
}

Show/Hide Modal​

http://localhost:3000/
import { useToggle } from 'react-power-ups';

export function DemoModal() {
const [isOpen, toggleModal] = useToggle();

return (
<>
<button onClick={toggleModal}>Open modal</button>

<div className={`modal-overlay ${isOpen ? 'block' : 'hidden'}`}>
<div className="modal">
<div>Hello 👋</div>
<button onClick={toggleModal}>Close</button>
</div>
</div>
</>
);
}

Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-toggle.ts