I want to create two components, one of them can (or maybe it just must) be used inside the other one. something like this:
Interface IChild {
name: string;
childKey?: string;
}
const Child: React.FC<IChild>= ({name,childKey})=>{
// do something here
}
Interface IParent {
}
const Parent: React.FC<IParent>=({children})=>{
return (
<div>
{React.Children.map(children, (child, index) => {
const item = child as ReactElement<PropsWithChildren<IChild>>;
if (item.type === Child) {
return cloneElement(item, { childKey:uuid() });
} else {
return child;
}
})}
</div>
)
}
Usage:
const App:React.FC<> = ()=>{
return (
<Parent>
<Child name="john"/>
<Child name="jane"/>
</Parent>
)
}
So when the Child is used inside the Parent, Parent will add the childKey prop, and when it's not used inside the Parent, childKey is not needed and is useless, I want to eventually publish this as a package, and don't want the end user to see the childKey prop, I just want to add it in case of Child is used inside the Parent, so the user should not see that prop. how can I do this? and should I do this?