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.

The message is:
Property 'props' does not exist on type 'ReactNode'. Property 'props' does not exist on type 'string'.
What I'm doing wrong?
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With