react-use-open
v1.1.2
Published
A simple React hook for managing open/closed states of components.
Readme
react-use-open
A simple React hook for managing open/closed states of components.
:zap: Fully typed. Developed in TypeScript with type definitions included and validated using tsd.
:sparkles: Test-driven. Comprehensive test coverage of the API.
Requirements
React >= 16.8.0Installation
NPM
npm install react-use-openYARN
yarn add react-use-openPNPM
pnpm add react-use-openUsage
useOpen
The hook function accepts an optional defaultValue argument, which sets the initial state. Default value is false (closed).
The hook returns an object containing the current state isOpen along with functions to manage the state: open, close and toggle.
Signature
function useOpen(defaultValue?: boolean): {
isOpen: boolean;
open: () => void;
close: () => void;
toggle: () => void;
};Examples
import React from "react";
import { useOpen } from "react-use-open";
function Accordion() {
const { isOpen, toggle } = useOpen(true);
return (
<>
<button onClick={toggle}>Toggle</button>
{isOpen && <p>Hidden text</p>}
</>
);
}import React from "react";
import { useOpen } from "react-use-open";
import { Modal } from "./Modal";
function Page() {
const { isOpen, open, close } = useOpen();
return (
<>
<button onClick={open}>Open modal</button>
<Modal open={isOpen} onClose={close} />
</>
);
}