Reputation: 1100
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
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