TheSpicyMeatball / react-nanny

Utils to manage your React Children
Other
85 stars 4 forks source link

Nested components are not picked up by getChildrenByTypeDeep #9

Closed dbrxnds closed 2 years ago

dbrxnds commented 2 years ago

Hi,

While using this library I ran into an issue, but I am not sure if this is just how it works or not. getChildrenByTypeDeep does not seem to pick up components that aren't direct children of the component you are calling it in.

Example: https://codesandbox.io/s/sharp-ptolemy-fx2sq?file=/src/App.tsx:207-228

Is this as intended? And if so, is there a way to work around this and still make it work, or is that just a limitation of how children works in React?

Otherwise great library, thanks!

TheSpicyMeatball commented 2 years ago

Hi @iDavidB,

Thanks for using react-nanny!

That is working as intended because Foo is a return value contained in NestedFoo and not a child of NestedFoo. If you had something like this, it would be included:

<NestedFoo>
  <Foo />
</NestedFoo>

...because that Foo would be considered a React child. I hope that makes sense!

Regarding what you could do to find that inner Foo, if instead of a NestedFoo component, you could make it a function, you could use getChildrenByTypeDeep. For example:

const renderNestedFoo = () => (
  <div>
    <Foo />
  </div>
);

export default function App() {
  return (
    <Tester>
      <Foo />
      <Foo />
      <Foo />
      {renderNestedFoo()}
    </Tester>
  );
}

Obviously, whether or not this would work for your situation depends on whether or not you own the current NestedFoo component in your app.

I hope this helps!