简体   繁体   中英

How do I check if Components child have child?

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?

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.

Eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM