useToggle

About

Toggle (between booleans or custom data)hook for React.

Examples

Basic usage

import "./styles.css";
import { useToggle } from "rooks";

export default function App() {
  const [state, toggle] = useToggle();

  return (
    <div className="App">
      <h1>Rooks: useToggle Example </h1>
      <br></br>
      <button onClick={toggle} style={{ cursor: "pointer" }}>
        {state ? <span>Yes! 👍</span> : <span>No! 👎</span>}
      </button>
    </div>
  );
}

With a Start value

import "./styles.css";
import { useToggle } from "rooks";

export default function App() {
  const [state, toggle] = useToggle(true);

  return (
    <div className="App">
      <h1>Rooks: useToggle Example </h1>
      <br></br>
      <button onClick={toggle} style={{ cursor: "pointer" }}>
        {state ? <span>Yes! 👍</span> : <span>No! 👎</span>}
      </button>
    </div>
  );
}

Custom toggle values

import "./styles.css";
import { useToggle } from "rooks";

export default function App() {
  const [state, toggle] = useToggle("on", value =>
    value === "on" ? "off" : "on"
  );

  return (
    <div className="App">
      <h1>Rooks: useToggle Example </h1>
      <br></br>
      <button onClick={toggle} style={{ cursor: "pointer" }}>
        {state}
      </button>
    </div>
  );
}

Arguments

ArgumentsTypeDescriptionDefault value
initialValuebooleanInitial value of the statefalse
toggleFunctionfunctionFunction which determines how to toggle a valuev => !v

Returned array items

Returned Array itemsTypeDescription
valueAnyCurrent value
toggleValuefunctionToggle function which changes the value to the other value in the list of 2 acceptable values. (Mostly true or false)

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel