Docs
Toggle

Toggle

A hook to toggle a boolean value

About

The useToggle hook takes a boolean value (true or false) and toggles it to the opposite value. It’s useful for actions that require toggling between two states, such as showing/hiding a modal, showing more/less text, or opening/closing a side menu.

Parameters

NameTypeDescription
initialValueboolean(Optional) The initial value of the toggle state.

Return Values

IndexTypeDescription
0booleanThe current state of the toggle.
1functionA function to toggle the state of the toggle.

Installation

Run the following command:

npx scriptkavi-hooks@latest add toggle

Usage

import { useToggle } from "@/hooks/toggle"
import * as React from "react"
 
function ToggleDemo({ on, toggle }) {
  return (
    <div>
      <label className="toggle">
        <input
          onChange={toggle}
          className="toggle-checkbox"
          type="checkbox"
          checked={on}
        />
        <div className="toggle-switch"></div>
        <span className="toggle-label">{on ? "On" : "Off"}</span>
      </label>
    </div>
  )
}
 
export default function App() {
  const [on, toggle] = useToggle(true)
 
  return (
    <section>
      <h1>UseToggle</h1>
      <button disabled={on} className="link" onClick={() => toggle(true)}>
        Turn On
      </button>
      <button disabled={!on} className="link" onClick={() => toggle(false)}>
        Turn Off
      </button>
      <button className="link" onClick={toggle}>
        Toggle
      </button>
      <button className="link" onClick={() => toggle("nope")}>
        (Also toggles)
      </button>
      <ToggleDemo toggle={toggle} on={on} />
    </section>
  )
}