https://github.com/arn4v/use-children
Filter React children for a specific component
https://github.com/arn4v/use-children
Last synced: 10 months ago
JSON representation
Filter React children for a specific component
- Host: GitHub
- URL: https://github.com/arn4v/use-children
- Owner: arn4v
- Created: 2021-07-12T20:30:40.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2021-07-13T14:37:33.000Z (almost 5 years ago)
- Last Synced: 2024-12-29T10:14:13.474Z (over 1 year ago)
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/use-children
- Size: 115 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-children
Filter React children for specific component
## Install
**NPM**:
```shell
npm install --save use-children
```
**Yarn**:
```shell
yarn add use-children
```
## Usage
Read the [Why?](#why) section for a more detailed explanation.
```jsx
import useChildren from "useChildren";
const ModalContent = () => {
return <>{/** Some JSX */}>;
};
const ModalOverlay = () => {
return <>{/** Some JSX */}>;
};
const ModalRoot = ({ children, isOpen }) => {
// withOverlay is an array of all ModalOverlay components
const [withOverlay] = useChildren(children, ModalOverlay);
// withContent is an array of all MdalContent components
const [withContent] = useChildren(children, ModalContent);
return (
{isOpen ? (
<>
{withOverlay}
{withContent}
>
) : null}
);
};
```
## Why?
Imagine you're building a Modal component which consists of three components:
1. ModalRoot - Portal component
2. ModalOverlay - Overlay component
3. ModalContent - The primary content container component
where the intended usage is the following:
```jsx
import { useState } from "react";
import { ModalRoot, ModalOverlay, ModalContent } from "../modal";
const MyModal = () => {
const [open, setOpen] = useState(false);
const openModal = () => setOpen(true);
const closeModal = () => setOpen(false);
return (
);
};
```
However, since ModalRoot does not force the user to pass in only ModalOverlay and ModalContent. The user can also do the following:
```jsx
import { useState } from "react";
import { ModalRoot, ModalOverlay, ModalContent } from "../modal";
const MyModal = () => {
const [open, setOpen] = useState(false);
const openModal = () => setOpen(true);
const closeModal = () => setOpen(false);
return (
Some content
);
};
```
With `use-children` you can filter for just `ModalContent` and `ModalOverlay`
## Credits
- [Geist-UI](https://github.com/geist-org/react) for the [pickChild](https://github.com/geist-org/react/blob/master/components/utils/collections.ts#L24) function