-1

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?

Sasgorilla
  • 2,403
  • 2
  • 29
  • 56

1 Answers1

0

You could identify them by setting their displayName property:

function Apple() { 
  return <div>Apple</div>
}
Apple.displayName = "apple"

function Banana() {
  return <div>Banana</div>
}
Banana.displayName = "banana"

Then when looping through children, check this property:

React.Children.forEach(children, child => {
  if (child.type.displayName == "banana") { console.log('I am a banana!) }
})

Demo:

Edit interesting-rosalind-9dp8y4

Spectric
  • 30,714
  • 6
  • 20
  • 43