bigblind bigblind - 3 months ago 20
React JSX Question

only allow children of a specific type in a react component

I have a

Card
component and a
CardGroup
component, and I'd like to throw an error when
CardGroup
has children that aren't
Card
components. Is this possible, or am I trying to solve the wrong problem?

Answer

You can use the displayName for each child, accessed via type:

for (child in this.props.children){
  if (this.props.children[child].type.displayName != 'Card'){
    console.log("Warning CardGroup has children that aren't Card components");
  }  
}
Comments