Jpark9061
Jpark9061

Reputation: 1100

React how to know how many child components a parent has?

If I try to use Object.keys(children).length and there is only 1 child component, then it gives me the amount of keys the one child component has. This approach only works if there are multiple child components. How would I find the amount of child component a component has?

<Navbar>
  <Component 1/>
</Navbar>
const Navbar = ({ children }) => {
  console.log(Object.keys(children).length);   //displays properly only if more than 1 child component
  console.log(children.length);                //undefined
  ...

Upvotes: 2

Views: 1167

Answers (1)

Harben
Harben

Reputation: 1856

React.Children.count method will help you get what you need.

const Navbar = ({ children }) => {
    child_count = React.Children.count(children)
}

https://reactjs.org/docs/react-api.html#reactchildren

Upvotes: 4

Related Questions