How do I check if Components child have child?

Viewed 217

I'm trying to clone a child of the component and add some props to it. But some of the child of this component are with child of their own. And because of that the new props are not cloned to it or to its children.

const component = () => {
      const child = componentProp(value, setValue);
      if (React.isValidElement(child)) {
        return React.cloneElement(child as any, {
          onBlur: onFocusChange,
          inputRef: searchInput,
        });
      }
      return child;
    };

How can I check if the child have children to be sure I can actually add the props to the correct level?

1 Answers

You can use React.Children.count(children) API

Returns the total number of components in children, equal to the number of times that a callback passed to map or forEach would be invoked.

E.g.

App.tsx:

import { Parent } from "./Parent";

export default function App() {
  return (
    <div className="App">
      <Parent
        child2={null}
        child={
          <div>
            <span>item1</span>
            <span>item2</span>
          </div>
        }
      />
    </div>
  );
}

Parent.tsx:

import React from "react";

export const Parent = ({ child, child2 }: any) => {
  console.log("child:", React.Children.count(child));
  console.log("child2: ", React.Children.count(child2));
  return child;
};

Output in the console:

child: 1
child2: 0
Related