Search code examples
javascriptreactjs

Check if React component is empty or has no child component


How do I check if a React component is empty or has no child component? For example if I have a component called Component A, how can I check if it contains Component B?


Solution

  • You can use this.props.children to get any child components. If there is only one child, this.props.children will point to that child component, otherwise it will return an array of child components.

    If its an array, you can use this.props.children.map to loop through them, and you can find the name, or type of the component like so:

    this.props.children.map(child => console.log(child.type))