Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly type React.Children and React.cloneElement?

I'm cloning my react children with cloneElement but I'm having some problems to type them.

This is my code(it is just passing a custom onClick function as a prop to the children):

const childrenWithProps = React.Children.map(children, child =>
  React.cloneElement(child as ReactChild, {
    onClick: (e: React.FormEvent) =>
      childrenClickHandler(
        e,
        child.props.children,
        onItemClick && onItemClick(e),
      ),
  }),
);

And this is my ReactChild type:

export type ChildProps = {
  onClick?: (e?: React.ChangeEvent<{}>) => void;
  props: React.Props<ReactChild>;
  children: ReactElement | ReactElement[];
};
export type ReactChild = ReactElement<ChildProps> | ReactElement;

And typescript keeps saying that there is a problem with my props on child.props.children.

enter image description here

The message is:

Property 'props' does not exist on type 'ReactNode'. Property 'props' does not exist on type 'string'.

What I'm doing wrong?

like image 817
ncesar Avatar asked Feb 03 '26 17:02

ncesar


1 Answers

The reason you're getting the message:

Property 'props' does not exist on type 'ReactNode'. Property 'props' does not exist on type 'string'.

Is because a ReactNode can be either a component, an html element, or a plain string. Strings don't accept props. I've found that all you have to do to clear it is properly type guard for a valid React Element:

const childrenWithProps = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
        return React.cloneElement(child, {newProp: 'myNewProp'})
    }

    return child;
});
like image 137
lawrence-witt Avatar answered Feb 05 '26 07:02

lawrence-witt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!