I want to create a packages like react-bootstrap.
<Card>
<Card.Title>Hello</Card.Title>
</Card>
I wish to create like below. But I couldn’t able to do.
<MyCustomComponent>
<MyCustomComponent.Header>
Header goes here
</MyCustomComponent.Header>
</MyCustomComponent>
interface Props {
children?: React.ReactNode | React.ReactNode[]
}
export const MyCustomComponent:FC<Props> = () => {
}
Props throwing error like .Header does not exist on type FC<Props & { children?: ReactNode; }>
React Version: ^18
3
Answers
Check React-bootstrap as reference of your code
Below code is from react-bootstrap’s form component :
As you see, React-bootstrap is using
Object.assign
function to assign differential components toForm
Component.So, in your case code should be:
Check MDN’s
Object.assign()
document for more.As you know in React > 18 children props was deleted from React.FC and you are able to use PropsWithChildren type (import it from React) like this:
And then to achieve the approach you want, you can follow like this:
And in other components, you can use it like this:
I would make
MyCustomComponent
require all of it’s children as props, and add them all to theMyCustomComponent
as a property, like so:It would then be consumed like this:
Suggested improvement – use the Context API
I would additionally recommend using the Context API to ensure that these children components are only rendered within their parent.
For a full working example that includes a custom context, check out this stackblitz project.
Youtube Video
This answer has been strongly guided by this YouTube video which I highly recommend giving a watch, to properly understand how the custom context can be utilised.