1.3.3 • Published 3 years ago

@react-hook/switch v1.3.3

Weekly downloads
2,605
License
MIT
Repository
github
Last release
3 years ago

A React hook for controlling a boolean value with toggle, on, and off callbacks. This is extremely useful for adding controlled/uncontrolled component behavior to components like <Checkbox/>, <Toggle/>, <Modal/>, etc.

Quick Start

import useSwitch from '@react-hook/switch'

// Basic usage
const Component = (props) => {
  const [value, toggle] = useSwitch(false /*default value*/)

  return (
    <>
      <span>Value: {value}</span>
      {/* toggles the current value to its opposite*/}
      <button onClick={toggle}>Toggle</button>
      {/* toggles the current value to true*/}
      <button onClick={toggle.on}>On</button>
      {/* toggles the current value to false*/}
      <button onClick={toggle.off}>On</button>
    </>
  )
}

// Creating a toggle component with a controlled and uncontrolled
// value pattern
const Toggle = ({value: controlledValue, defaultValue, onChange}) => {
  const [value, toggle] = useSwitch(defaultValue, controlledValue, onChange)

  return (
    <>
      <span>Value: {value}</span>
      <button onClick={toggle}>Toggle</button>
      <button onClick={toggle.on}>On</button>
      <button onClick={toggle.off}>On</button>
    </>
  )
}

API

useSwitch(defaultValue?, controlledValue?, onChange?)

function useSwitch(defaultValue?: boolean, controlledValue?: boolean, onChange?: (value: boolean, prevValue: boolean) => any): readonly [boolean, (() => void) & {
    on: () => void;
    off: () => void;
}]

Arguments

ArgumentTypeDefaultRequired?Description
defaultValuebooleanfalseNoSets the default value of the switch
controlledValuebooleanundefinedNoSets the controlled value of the switch, which will override the defaultValue
onChange(value: boolean) => anyundefinedNoA callback invoked whenever toggle callbacks that change state are invoked

Returns [value: boolean, toggle: Toggle]

VariableTypeDescription
valuebooleanDefines the initial value
toggle() => void & {on: () => void, off: () => void}If the value is true, calling this will make it false and vice-versa

() => void & {on: () => void, off: () => void}

MethodTypeDescription
on() => voidSwitches the value to true
off() => voidSwitches the value to false

LICENSE

MIT