'hide a prop from user view in typescript react

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?



Solution 1:[1]

Probably the only way to do that is to wrap child in fragment and set fragment's key.

// Parent.tsx

import React from "react";
import { Child } from "./Child";

interface IParent {}

export const Parent: React.FC<IParent> = ({ children }) => {
  const childs = React.Children.map(children, (child) => {
    if (!React.isValidElement(child)) {
      return null;
    }

    if (child.type === Child) {
      return <React.Fragment key={`UUID-${uuid()}`}>{child}</React.Fragment>;
    }

    return child;
  });

  return <div>{childs}</div>;
};

Then if (child.key?.startsWith("UUID-")) { /* ... */ }

CodeSandbox

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1