If I have a generic component that will supply some prop to an arbitrary child component at runtime like:
const GenericComponent = <T extends {id: string}>(props: {fetch: () => T, child: React.ReactElement}) => {
const {id} = props.fetch()
return (
<div>{ props.child }</div> // <------------- how to pass in argument here?
)
}
with a child component that looks like this:
const PassedInComponent = (props: {id: string}) => {
return (
<div>{props.id}</div>
)
}
What is the best way of achieving this?
From other Stackoverflow answers like this, I know I can pass in the child component with an empty id
prop, then clone it with new arguments in the generic component:
<GenericComponent fetch={...} child={<PassedInComponent id={""} />} /> // <--- empty id prop passed in here
const GenericComponent = <T extends {id: string}>(props: {fetch: () => T, child: React.ReactElement}) => {
const {id} = props.fetch()
return (
<div>{ React.cloneElement(props.child, {id: id}) }</div> // <---- can clone the element and pass in new arguments like this
)
}
This example is pretty contrived but unfortunately I have to deal with this scenario due to other constraints.
My question is: supplying a child component with a dummy prop, then overwriting that props with 'React.cloneElement' seems pretty bad. Is there a better way of going about this?