Design comparison
SolutionDesign
Solution retrospective
I decide to take the qr code
card challenge to study compound components pattern with React and Typescript.
Looking at the code I was able to type the parent component <Card/>
with the child that composes the parent:
interface Card {
children: ReactNode
}
interface CardComposition {
Image: typeof CardImage
Content: typeof CardContent
}
export const Card: React.FC<Card> & CardComposition = ({ children }) => {
return (
<div className="card">
{children}
</div>
)
}
and pass each child to the parent
Card.Image = CardImage
Card.Content = CardContent
my question would be how could I enforce the child components (CardImage
and CardContent
) to be used ONLY inside of the Card
component and throw an error when that happens?
I've tried to use React.Children.map...
but it seems a bit odd...
but in general, I've enjoyed creating this component and use this pattern 👍🏾
Community feedback
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord