react-on-off-state

0.0.2 • Public • Published
react-on-off-state

React component to manage on/off states

Travis Codecov npm version code style: prettier

Installation

npm install react-on-off-state
# or 
yarn add react-on-off-state

Usage

import React from "react";
import ReactDOM from "react-dom";
import OnOffState from "react-on-off-state";
 
ReactDOM.render(
  <OnOffState>
    {({ on, toggle }) => (
      <>
        <h1>{on ? "Red" : "Blue"}</h1>
        <button onClick={toggle}>Change pill</button>
      </>
    )}
  </OnOffState>,
  document.getElementById("root")
);

Props

defaultOn

boolean | optional, defaults to false

The initial on state.

on

boolean | optional, control prop

By default, react-on-off-state manages its own state. You can use the on prop if you want to control the state by yourself.

onChange

(on: boolean) => any | optional

Called whenever the state changes.

  • on: boolean – The new state

children

(options: RenderOptions) => React.Node | required

The children prop is treated as a render prop. This is where you render whatever you want based on the state of react-on-off-state.

  • options: RenderOptions – An object with the following properties:
Property Description
on: boolean true if the state is on, false otherwise
off: boolean convenience prop if you need !on
setOn: () => void Sets the state to on
setOff: () => void Sets the state to off
toggle: () => void Toggles the state (i.e. when it's on, will set to off and vice versa)

Inspiration

The design and API mostly comes from react-toggled. react-on-off-state is a more generic version of it that only manages state and nothing more. You can think of it as a pre-build state machine. It's useful whenever you want to render not just a toggle component but anything that has two states.

LICENSE

MIT

Readme

Keywords

Package Sidebar

Install

npm i react-on-off-state

Weekly Downloads

1

Version

0.0.2

License

MIT

Unpacked Size

14.9 kB

Total Files

5

Last publish

Collaborators

  • cangoektas