Extended utils for ⚛️ React.Children data structure that adds recursive filter, map and more methods to iterate nested children.

Overview

React Children Utilities

Gzip Bundle Size Build Status Test Coverage Status Known Vulnerabilities

All Contributors npm version npm downloads

Recursive and extended utils for React children opaque data structure.

Installation

Available as a package and can be added to your application with npm or yarn after installing the peer dependency react

# with yarn
yarn add react-children-utilities react

# with npm
npm install --save react-children-utilities

Usage

This package extends the existing React.Children utilities, you can import it as a whole.

import React from 'react';
import Children from 'react-children-utilities';

const MyComponent = ({ children }) => {
  const onlySpans = Children.filter(children, (child) => child.type === 'span');
  return <div>{onlySpans}</div>;
};

Also you can import only the function you need

import React from 'react';
import { filter } from 'react-children-utilities';

const MyComponent = ({ children }) => {
  const onlySpans = filter(children, (child) => child.type === 'span');
  return <div>{onlySpans}</div>;
};

API documentation

Contributors

Thanks goes to these wonderful people (emoji key):


Fernando Pasik

🐛 💻 📖 🤔

mrm007

🐛 💻

yosef langer

🐛 💻

iyegoroff

🐛 💻

Mark Allen

🐛 💻

Ryosuke IWANAGA

🐛 💻

Daniel Pinyol

🐛 💻

Brian Bartholomew

🐛 💻

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT (c) 2018 Fernando Pasik

Issues
  • ESM issue 😬

    ESM issue 😬

    Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/kud/Projects/_kud/diary/node_modules/react-children-utilities/react-children-utilities.js
    require() of ES modules is not supported.
    require() of /Users/kud/Projects/_kud/diary/node_modules/react-children-utilities/react-children-utilities.js from /Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
    Instead rename react-children-utilities.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/kud/Projects/_kud/diary/node_modules/react-children-utilities/package.json.
    
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1192:13)
        at Module.load (internal/modules/cjs/loader.js:1040:32)
        at Function.Module._load (internal/modules/cjs/loader.js:929:14)
        at Module.require (internal/modules/cjs/loader.js:1080:19)
        at require (internal/modules/cjs/helpers.js:72:18)
        at Object.react-children-utilities (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:1528:18)
        at __webpack_require__ (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:23:31)
        at Module../src/lib/get-reading-time.js (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:1017:82)
        at __webpack_require__ (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:23:31)
        at Module../src/components/Layout/Post/index.js (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:355:79)
        at __webpack_require__ (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:23:31)
        at Module../src/pages/_app.js (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:1075:82)
        at __webpack_require__ (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:23:31)
        at Object.0 (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:1395:18)
        at __webpack_require__ (/Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:23:31)
        at /Users/kud/Projects/_kud/diary/.next/server/static/development/pages/_app.js:91:18 {
      code: 'ERR_REQUIRE_ESM'
    }
    
    question wontfix 
    opened by kud 21
  • Compilation errors when building with webpack 5

    Compilation errors when building with webpack 5

    Hi @fernandopasik, thanks for your project, it's pretty useful. We are using your code in order to traverse React trees in runtime and do some stuff to adapt dynamically how a chat must be shown depending on a messaging provider (Facebook, Whatsapp, ...).

    Expected behavior

    It should work correctly with Webpack 5.9.0. Maybe transpiled lib should preserve the file extension in order to not break with webpack.

    Current behavior

    We are now trying to migrate our projects to Webpack 5 and we have experienced the following kind of errors:

    ERROR in ./node_modules/react-children-utilities/react-children-utilities.js 10:0-38
    Module not found: Error: Can't resolve './lib/onlyText' in '/.../.../.../.../botonic-examples/blank/node_modules/react-children-utilities'
    Did you mean 'onlyText.js'?
    BREAKING CHANGE: The request './lib/onlyText' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
    

    Steps to reproduce

    1. Init a project with Webpack 5.9.0.
    2. Configure babel (for example):
    const babelLoaderConfig = {
      exclude: /node_modules[\/\\](?!(@botonic)[\/\\])/,
      use: {
        loader: 'babel-loader',
        options: {
          cacheDirectory: true,
          presets: ['@babel/preset-env', '@babel/react'],
          plugins: [
            '@babel/plugin-proposal-object-rest-spread',
            '@babel/plugin-proposal-class-properties',
            'babel-plugin-add-module-exports',
            '@babel/plugin-transform-runtime',
          ],
        },
      },
    }
    
    1. Try to compile the project with webpack.

    Device information

    • OS: MacOs
    • Version: Node v12.20.0

    Possible solution

    If not fully necessary, do not specify type module in package.json. Otherwise, publish lib with it's corresponding extensions. Related issues (solutions proposed didn't work for me): https://github.com/graphql/graphql-js/issues/2721

    In fact, changing manually the following code inside node_modules fixed the issue:

    import { Children, isValidElement } from 'react';
    import hasChildren from './hasChildren';
    

    to

    import { Children, isValidElement } from 'react';
    import hasChildren from './hasChildren.js';
    
    bug 
    opened by vanbasten17 11
  • Build issue during Jest tests when importing react-children-utilities

    Build issue during Jest tests when importing react-children-utilities

    Describe the bug Importing any file from react-children-utilities results in a build error when running the jest test suite.

        D:\new-create-react-app\node_modules\react-children-utilities\react-children-utilities.js:1
        ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Children } from 'react';
                                                                                                        ^
    
        SyntaxError: Unexpected token {
    
          3 | import './App.css';
          4 |
        > 5 | import { deepMap } from 'react-children-utilities';
            | ^
          6 |
          7 | function App() {
          8 |   return (
    
          at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
          at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
          at Object.<anonymous> (src/App.js:5:1)
    

    I am unclear whether this issue exists in react-children-utilities or whatever it is a configuration problem with jest, but a default installation of create-react-app also results in this issue. Builds etc are fine, only the jest test is broken.

    There are various tickets https://github.com/facebook/jest/issues/6229 discussing this problem, however none of the suggestions work for this particular library.

    To Reproduce Steps to reproduce the behavior:

    1. Install a new project from https://github.com/facebook/create-react-app (npx create-react-app my-app)
    2. Eject the application (yarn eject)
    3. At this point running yarn run test should pass all tests
    4. yarn add react-children-utilities
    5. Update /src/App.js to import anything from react-children-utilities, for example: import { deepMap } from 'react-children-utilities';
    6. At this point running yarn run test will fail with the above error.
    question 
    opened by deleemillie 10
  • groupByType support UppercaseComponent, not only lowercase like div + span

    groupByType support UppercaseComponent, not only lowercase like div + span

    Feature Request

    Problem to solve

    Be able to use groupByType on custom components. Currently only works on native/lowercase react elements/nodes like div, span, p, li, etc.

    Consider

    <MyComponent>
      <MyTab />
      <MyTab />
      <MyButton />
      <p />
      <p />
    </MyComponent>
    

    groupByType(children) inside MyComponent could return:

    {
      MyTab: [<MyTab />, <MyTab />],
      MyButton: [<MyButton />],
      p: [<p />, <p />],
    }
    

    Possible implementation

    Currently you can easily use lodash.groupBy and React.Children.toArray to accomplish this:

    groupBy(Children.toArray(children), (child) => child.type.name)
    

    Footnote

    Any caveats or reasons this wouldn't work or shouldn't be implemented? I could probably try implementing and submit PR if it would be accepted

    feature 
    opened by TSMMark 8
  • fix: add test and fix for empty child for onlyText

    fix: add test and fix for empty child for onlyText

    Closes #18.

    Description

    Codesandbox example of the issue

    Self-closing components caused this error

    Converting circular structure to JSON
        --> starting at object with constructor 'FiberRootNode'
        |     property 'current' -> object with constructor 'FiberNode'
        --- property 'stateNode' closes the circle
    

    I added a test that tests the method when the child is self-closing. The fix I add is in the area that checks for nested children. I added a check that it is an element but does not have children. At that point, I decided to return an empty string.

    I feel this may be a bandaid because self-closing components often take props to make additional children and return a much larger nested structure. I am not sure we have access to this info in the child at this point.

    opened by bcbrian 7
  • How to get deep children

    How to get deep children

    Is this meant to be used when testing? Can't otherwise see how to get children recursively, at least children is not deep in my experiments.

    question 
    opened by einarq 5
  • Any opportunity for a deepFilter?

    Any opportunity for a deepFilter?

    I would like to iterate over all children of an element and then filter it down to components of a particular type. Any opportunity to extend the library?

    feature 
    opened by dptoot 5
  • fix: pass index & children to deepMap, deepForeach & deepFind

    fix: pass index & children to deepMap, deepForeach & deepFind

    Suggested implementation of #16

    opened by dpinol 5
  • deepMap, deepFind and deepForEach do not use index & children arguments

    deepMap, deepFind and deepForEach do not use index & children arguments

    The deepMap & deepFind specify index & children arguments for the function that need to be passed. However, this arguments are not specified when calling the functions. In deepForEach the same happens for the index argument.

    Expected behavior

    The callback functions should be called with (currentNode, index, children)

    Current behavior

    The callback functions are called with (currentNode)

    Possible solution

    https://github.com/fernandopasik/react-children-utilities/pull/17

    bug 
    opened by dpinol 5
  • added typescript typings

    added typescript typings

    Added typescript types for your library so it can be conveniently used in typescript environments.

    thank you for your work.

    opened by vasilevich 4
  • `deepMap` not iterating over elements with only text as children.

    `deepMap` not iterating over elements with only text as children.

    Consider the following elements,

    <p className="test1">Test text 1</p>
    <p className="test2">Test text 2 <span>Test text 3</span> test text 4</p>
    

    I use deepMap over each element and console.log each child as it is iterated over. In the first case it only iterates over the <p> element.

    In the second case it iterates over three elements: the "Test text 2" at the start, the <span> element and the "test text 4" at the end.

    Is this the intended behaviour?

    In the first case I would have thought that the "Test text 1" text was a child of the <p> tag, and therefore deepMap should recurse again over the "Test text 1" child.

    In the second case I would have thought that deepMap should recurse into the "Test text 3" text inside the <span> element since I would have thought that the "Test text 3" text was a child of <span>.

    bug 
    opened by Yharooer 3
React-Godfather aims to explore an alternative mental model for function components.

React-Godfather "Look ma, no Hooks!" React-Godfather aims to explore an alternative mental model for function components. It adds a thin layer between

John Kapolos 17 Sep 20, 2021
Collection of Google fonts as typeface data for usage with three.js, react-three-fiber, and other tools.

Collection of Google fonts as typeface data for usage with three.js, react-three-fiber, and other tools.

Components AI 44 Oct 3, 2021
🌊🐷 Utility for generalized composition of React components

???? Utility for generalized composition of React components

Enki 279 Oct 4, 2021
🤖 React Native Android widgets bridged to JS, a proof of concept

React Native Android Widget Proof Of Concept ?? Using React Native and having Android widgets is possible. Create buttons in Java / Android XML to tri

Netbeast 186 Sep 21, 2021
HTML to React parser that works on both the server (Node.js) and the client (browser):

HTML to React parser that works on both the server (Node.js) and the client (browser):

Mark 1k Oct 19, 2021
Article converter is an api for getting a extended html version of the content attribute provided by Article API.

Article converter is an api for getting a extended html version of the content attribute provided by Article API.

NDLA 2 Oct 6, 2021
A lightweight react library that converts raw HTML to a React DOM structure.

A lightweight react library that converts raw HTML to a React DOM structure.

Arve Knudsen 652 Oct 17, 2021
The next generation state management library for React

The next generation state management library for React

Bytedance Inc. 150 Sep 18, 2021
Flatten a React "pyramid of doom" by composing multiple layers into a single component.

Flatten a React "pyramid of doom" by composing multiple layers into a single component.

new Chris(A) 4 Oct 5, 2021
Because your state management code should be domain-agnostic.

Because your state management code should be domain-agnostic.

Zachary DeRose 3 Oct 6, 2021
CSS media queries for React

react-media react-media is a CSS media query component for React. A <Media> component listens for matches to a CSS media query and renders stuff based

React Training 2.4k Oct 15, 2021
React-Native library for the WidgetKit framework. Integrate a Widget into your App 🍏📱

react-native-widgetkit React-Native Library for the iOS ?? WidgetKit framework Table of Contents ?? Introduction ??‍?? Installation ??‍ Usage ????‍??

Fasky 82 Oct 13, 2021
A Fetch Library Support React New Suspense SSR

use-suspense-fetch A data fetching library for React Suspense. inspired by use-asset Feature use LRU Cache support create custom cache support React 1

Snake 6 Jul 12, 2021
iOS Today Widget in React Native

React Native Today Widget Experimental library investigating limits of implementation iOS App Extensions using React Native. Sample result from Comple

Matěj Kříž 345 Oct 21, 2021
@custom-elements-manifest/analyzer plugin to ✨ automatically ✨ create react wrappers for your custom elements

cem-plugin-reactify @custom-elements-manifest/analyzer plugin to automatically create React wrappers for your custom elements based on your custom ele

Pascal Schilp 7 Oct 6, 2021
A simple Facebook Chat Head like bubble for react native

react-native-floating-bubble A simple Facebook Chat Head like bubble for react native. Special thanks to bubble-for-android because this is just react

null 109 Oct 14, 2021
A React wrapper for signature pad

react-signature-pad-wrapper A React wrapper for signature pad. Installation This package is available through npm: npm install --save react-signature-

Michael Dzjaparidze 64 Oct 14, 2021
Detect device, and render view according to detected device type.

react-device-detect Detect device, and render view according to the detected device type. Installation To install, you can use npm or yarn: npm instal

Michael Laktionov 1.6k Oct 14, 2021
React Refresh Token with JWT and Axios Interceptors example

Buid React JWT Refresh Token example with Axios Interceptors - Refresh Token in React.js, Axios silent refresh JWT token example

null 18 Sep 30, 2021