Reputation: 4260
When a component clones its children to inject props into them, how to define the children props type?
I'm receiving an error cause injectedProps
is expected in Child
const Parent: React.SFC<ParentProps> = ({ children }) => (
<div>
{React.cloneElement(children[0], { injectedProp: 'foo' })}
</div>
);
const Child: React.SFC<ChildProps> = ({ injectedProp }) => (
<div attr={injectedProp} />
);
type ChildProps = {
injectedProp: string;
};
<Parent>
<Child />
</Parent>
Error in Child:
injectedProp
is missing
Upvotes: 5
Views: 1948
Reputation: 30879
This code pattern can't be typed properly in TypeScript and is ugly if you ask me. Instead, consider passing a function that takes the injected prop and creates the final children:
interface ParentProps {
children: (childProps: ChildProps) => React.ReactNode;
}
const Parent: React.SFC<ParentProps> = ({ children }) => (
<div>
{children({ injectedProp: 'foo' })}
</div>
);
const Child: React.SFC<ChildProps> = ({ injectedProp }) => (
<div title={injectedProp} />
);
type ChildProps = {
injectedProp: string;
};
function foo() {
return <Parent>
{childProps => <Child {...childProps} />}
</Parent>
}
Upvotes: 2