Say I have apples and bananas:
function Apple() {
return <div>Apple</div>
}
function Banana() {
return <div>Banana</div>
}
I want to put some in a <FruitSalad>
:
<FruitSalad>
<Apple>
<Apple>
<Banana>
</FruitSalad>
How can I check their type at run time?
function FruitSalad({children}: {children: React.ReactNode}) {
React.Children.map(children, child => {
if (isBanana(child)) { console.log('I am a banana!') }
})
return <div>{children}</div>
}
function isBanana(element: any): element is JSX.Element {
return React.isValidElement(element) && ???
}
What is the definition of isBanana()
here? Relying on the name of anything ("Banana") is problematic because it may break when code is minified in production. So what's a safe way to see if a child is a Banana
component?