react-on-off-state
v0.0.2
Published
React component to manage on/off states
Downloads
4
Readme
React component to manage on/off states
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 tofalse
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