Typescript errors with `cloneElement`

Hi all 👋 So while building my app I faced an issue that really put my UI at test. As I am sure many of you already experienced, the design of our application (even if we're the ones creating it) is able to account only for a small amount of cases. For example, I designed a card where the text can grow quite a lot and am figuring out the best approach. Specific to this request though is the fact that when I use the cloneElement and I try to set a new className I get the following error message: Argument of type '{ className: string; }' is not assignable to parameter of type 'Partial<unknown> & Attributes' Here's my code:
const massagedChildren = Array.isArray(children)
? children.map((child: ReactNode) => {
if (!isValidElement(child)) return child;

return cloneElement(child, {
className: cn(child.props.className, { block: isOverflowing }),
});
})
: null;
const massagedChildren = Array.isArray(children)
? children.map((child: ReactNode) => {
if (!isValidElement(child)) return child;

return cloneElement(child, {
className: cn(child.props.className, { block: isOverflowing }),
});
})
: null;
If you need I can give you more context about why this code it's useful for my app, but I don't think it's related with the issue. Thanks for the help 🙏 PS: that code also has an error for child.props.className because it gets inferred an any type for child even though I check with isValidElement just few lines above.
1 Reply
cupofcrypto
cupofcrypto15mo ago
To whom would be interested in the future this is how I solved the errors. Not proud because I am not sure it is the best code, but at least it gets the job done.
// Made in order to solve some issues with `cloneElement`
type ChildrenProps = {
className?: string;
};

children.map((child: ReactElement<ChildrenProps>) => {
if (!isValidElement(child)) return child;

return cloneElement(child as ReactElement, {
className: cn(child.props.className as ClassValue, {
block: isOverflowing,
}),
});
});
// Made in order to solve some issues with `cloneElement`
type ChildrenProps = {
className?: string;
};

children.map((child: ReactElement<ChildrenProps>) => {
if (!isValidElement(child)) return child;

return cloneElement(child as ReactElement, {
className: cn(child.props.className as ClassValue, {
block: isOverflowing,
}),
});
});
Want results from more Discord servers?
Add your server