Introduction
use-disclosable
is a react library that allow to easily manage disclosable elements.
It provide a simple API that allow you to quickly integrate any disclosable elements (custom or from a library) into your application.
Phylosophy
Classic approach
Let's take a look at the following example:
MyComponent.tsx
1import { useState } from 'react';
2import MyDialogElement from './MyDialogElement';
3
4export const MyComponent = () => {
5 const [isOpen, setIsOpen] = useState(false);
6 return (
7 <div>
8 <button onClick={() => setIsOpen(true)}>Open dialog</button>
9 <MyDialogElement isOpen={isOpen} onClose={() => setIsOpen(false)} />
10 </div>
11 )
12}
In a classic approach, when we want to interact with a disclosable element, we have to manage the open state and mount the element early in the component tree.
Using this approach mean we have to manage every state by hand and we have to keep the element mounted in the component tree even if it's lifespan is relatively short.
Also when dialog require some specific props, we have to pass them to the element and handle case where their could be undefined
.
use-disclosable approach
This library has a slightly different approach:
-
- The disclosable element should be mounted close to the body and not inside page components. Since "disclosable" should appear in the top layer.
-
- The disclosable element should be mounted in the component tree only when it's open.
-
- The open state of the component tree should be defined by if he is mounted or not
Here a brief overview of the general idea:
Here what's the above example will look like with use-disclosable
:
1import { useDisclosable } from 'use-disclosable';
2import MyDialogElement from './MyDialogElement';
3
4const MyComponent = () => {
5 const { open } = useDisclosable();
6
7 return (
8 <div>
9 <button onClick={() =>open(MyDialogElement)}>Open</button>
10 </div>
11 )
12}