Git Product home page Git Product logo

react-children-utilities's People

Contributors

bcbrian avatar dependabot[bot] avatar dpinol avatar fernandopasik avatar iyegoroff avatar mrm007 avatar riywo avatar tsmmark avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-children-utilities's Issues

deepFilter doesn't match to grandchildren

Bug Report

deepFilter doesn't match to grandchildren. Is this expected?

Expected behavior

<div>
  <span>1</span>
  <span>2</span>
  <span>3</span>
</div>

Current behavior

<div>
  <span>1</span>
  <span>2</span>
</div>

Steps to reproduce

Run this.

import React from "react";
import { render } from "react-dom";
import { deepFilter } from "react-children-utilities";

type DeepFilteredProps = Readonly<{
	children: React.ReactNode;
}>;

const DeepFiltered: React.VFC<DeepFilteredProps> = ({ children }) => {
	return <div>{deepFilter(children, item => item && (item as React.ReactElement).type === "span")}</div>;
}

const Example: React.VFC = () => {
	return (
		<DeepFiltered>
			<span>1</span>
			<span>2</span>
			<div>
				<span>3</span>
			</div>
		</DeepFiltered>
	);
}

render(<Example />, document.body);

Possible solution

If this is expected, I think the example of deepFilter should be updated.

deepMap and deepFind does not appear to be going deep

It appears deepMap and deepFind, doesn't go deep, however deepForEach does.

Children.deepMap(children, child => { console.log('deepFind type', child.type); return child; });

Children.deepFind(children, child => { console.log('deepFind type', child.type); return false; });

getElementName is not exported

Bug Report

getElementName is not exported

Expected behavior

getElementName is exported

Current behavior

getElementName is not available for import.

Steps to reproduce

import { getElementName } from "react-children-utilities"

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?

Support named imports by exporting named constants

Currently you have to import this way:

import Children from 'react-children-utilities'

It would be great if we could import named exports like:

import { onlyText } from 'react-children-utilities'

It should be easy for this module to use es6 named exports, something like this:

/**
 * Filter children
 * @param   {object} children - React component children
 * @param {function} filterFn - Array filter callback
 * @returns  {array}          - Filtered children
 */
export function filter(children: number, filterFn: (child: Node) => boolean): Node {
  return Children
    .toArray(children)
    .filter(filterFn);
};

export default {

  ...Children,

  filter,
  etc,
  etc,
  etc,
  onlyText,

};

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): graphql/graphql-js#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';

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.

`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>.

Problem with husky on npm 7.20.*

Bug Report

Hello, I am having a problem using npm v7.20.3 with react-children-utilities v2.5.4. As I show in the next image, npm install can't finish because there is a problem with husky library. This error only happens with npm 7.20., if I downgrade to npm 6..* my install finish correctly. I have tried installing husky manually, globally, but it is still failing.

I am looking for a way to solve this in order to update to npm 7.20.*

Screen Shot 2021-07-30 at 10 00 44

Steps to reproduce

  1. Update npm to v7.20.3
  2. Install this library in your project
  3. Maybe delete node_modules and npm install again

Any help would be highly appreciated :D, sorry if I am missing something.

Issues with "deep children" (aka children within other component)

Describe the bug
As described here #1 and here #3, there are some issues with searching deep.

I have tried the sample given in #3 (comment) and unfortunately it doesn't work (using React 16.8.6).

To Reproduce
I have the sample running here: https://codesandbox.io/s/busy-hypatia-gvdre

The problem seems to be that child.props.children is not set, when we reach a functional/class component - as it's children are not provided, but evaluated on render.

I don't know if this has been otherwise in earlier versions of React, or if there's a work around.

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 jestjs/jest#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.

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

`deepForEachFn` does not accept `children` argument as mentioned in the docs.

Bug Report

deepForEachFn does not match the docs as it does not accept a children argument.

The docs say:

deepForEach(
  children: ReactNode | ReactNode[],
  forEachFn: (child: ReactNode, index?: number, children?: ReactNode[]): void,
): void

However, in deepForEach.d.ts:

declare const deepForEach: (children: ReadonlyDeep<ReactNode | ReactNode[]>, deepForEachFn: (child: ReadonlyDeep<ReactNode>, index?: number | undefined) => void) => void;

Can't resolve 'react'

Describe the bug

When bundling:

ERROR in ../node_modules/react-children-utilities/dist/index.js
Module not found: Error: Can't resolve 'react' in '/Users/memect-webdeveloper/repo/MemectSites/node_modules/react-children-utilities/dist'
 @ ../node_modules/react-children-utilities/dist/index.js 1:278-294

To Reproduce
Steps to reproduce the behavior:

  1. Create a react storybook
  2. import { onlyText } from 'react-children-utilities';
  3. start the storybook

Expected behavior

Import without error

Device (please complete the following information):

  • Type: desktop
  • OS: MacOS
  • Browser Firefox
  • Version 67

deepFind should return the element found, not its root

Is your feature request related to a problem? Please describe.
I'd like to get an element which has specific props from children by deepFind. I assumed it returns the element which is matched agains the test function, but actually it returns its root i.e.

Expected:

          <i>3</i>

Actual:

        <span>
          <i>3</i>
        </span>

Describe the solution you'd like
Change deepFind behaviour to return the found element instead of its root element. (Or introduce a new function like deepElementFind)

Describe alternatives you've considered
I could use deepForEach but it visits all elements unnecessarily.

Additional context
I found #1 but I'm not sure the current behaviour is expected. If not, it is a bug.

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

#17

Deepmap nested children

If I have a custom component as a child, when I use deepMap, its children are not being iterated. Eg:

<MyComponent>
    <User/>
</MyComponent>

Where user contains two input fields. When I use deepMap(children) inside MyComponent user inputs are not included. Is it possible to deepMap while there is a component inside?

onlyText does not support self closing children

Self-closing elements break onlyText method
Codesandbox example

Expected behavior

Self-closing elements should return an empty string unless we can get into the nuts and bolts of it.

Current behavior

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

Steps to reproduce

Codesandbox example

  1. Add react-children-utilities to project
  2. import {onlyText} from "react-children-utilities";
  3. Use only text with a child that is self-closing

Device information

  • Type: all
  • OS: windows, mac
  • Browser: chrome, safari
  • Version: most recent

Possible solution

#19

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'
}

ts type

Bug Report

Define the error after building

Expected behavior

Current behavior

Steps to reproduce

  1. Source code
    image
  2. Definition of code after building this package
    image
  3. When I use this package to build my own code definition, will report an error.
    image
    image
    image

Possible solution

deepFilter recursion failed on user defined Component

Bug Report

The test below will failed.

  function Comp(props: ComponentProps<'span'>) {
    return <span {...props} />;
  }

  it('nested elements', () => {
    const DeepFiltered: FC<Props> = ({ children }) => (
      <div>{deepFilter(children, (item: ReactNode) => (item as ReactElement).type === 'span')}</div>
    );

    const element = TestRenderer.create(
      <DeepFiltered>
        <span>1</span>
        <span>2</span>
        <Comp>
          <strong>3</strong>
          <span>
            <strong>4</strong>
            <span>5</span>
          </span>
        </Comp>
      </DeepFiltered>,
    );
    const { children } = element.toJSON() as ReactTestRendererJSON;

    expect(children).toMatchInlineSnapshot(`
      Array [
        <span>
          1
        </span>,
        <span>
          2
        </span>,
        <span>
          <span>
            <span>
              5
            </span>
          </span>
        </span>,
      ]
    `);
  });

Expected behavior

deepFilter should be also work on user defined Component.

Current behavior

 ● deepFilter › nested elements

    expect(received).toMatchInlineSnapshot(snapshot)

    Snapshot name: `deepFilter nested elements 1`

    - Snapshot  - 7
    + Received  + 0

    @@ -3,13 +3,6 @@
          1
        </span>,
        <span>
          2
        </span>,
    -   <span>
    -     <span>
    -       <span>
    -         5
    -       </span>
    -     </span>
    -   </span>,
      ]

      35 |     const { children } = element.toJSON() as ReactTestRendererJSON;
      36 |
    > 37 |     expect(children).toMatchInlineSnapshot(`
         |                      ^
      38 |       Array [
      39 |         <span>
      40 |           1

      at Object.<anonymous> (src/lib/__tests__/deepFilter.spec.tsx:37:22)

onlyText: reduce calls of validate fn

Report

We did call React.isValidElement() more than one:

  1. In first condition – two times. Because hasChildren() call React.isValidElement() too.
  2. In second condition – four times. Because we recall React.isValidElement() in the place and than in hasChildren().

Possible solution

We can call React.isValidElement() once, save the result to variable and than reuse them. And we shouldn't use hasChildren().

react 18 support request

Is there any way to support react 18 soon?

Looks like we just have to update the peerDependencies version

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.