An open API service indexing awesome lists of open source software.

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

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