I'd like to make a functional component which gives a prop to its immediate children. I don't want to use a context because I want it to only be available to the immediate children.
So given the following components:
const TopLevel = () => {
return (
<FooGiver>
<LowerLevel />
</FooGiver>
)
}
interface LowerLevelProps {
foo?: string;
}
const LowerLevel = ({foo}: LowerLevelProps) => {
return foo ? <p>{foo}</p> : <p>No foo provided</p>
}
const FooGiver = ({ children }: FooGiverProps) => {
const foo = bar // TODO: This should set its children's `foo` prop to "bar"
return (
<>
{ children }
</>
)
}
Is it possible to define FooGiver such that it will give any children it receives a foo prop of "bar"?
If so, would I need to continue to keep the foo prop optional, or would TS pick up that FooGiver will always set foo, and not complain that I called <LowerLevel /> without providing the required foo prop?
I think this would do it to add props to all children
The following example component adds a new props named newProp with value true to all children it takes.
function Parent({children}){
return <>
{children.map(child=>{
const modified = child;
modified.props["newProp"] = true;//add new value to prop
return modified
})}
</>
}