1 minute read

I was building a Reactjs component, that should toggle between two child components.

<Toggle>
	<Comp1>
	<Comp2>
</Toggle>

The render method of Toggle looked like this

render() {
	const content = React.Children.count(this.props.children) > 0 ? this.props.children[0] : this.props.children[1];

	return (
		${content}
	);
}

Unfortunately, this didn’t work (index out of bounds), when I passed only one component instead of two. This doesn’t make sense, since the Toggle is supposed to toggle between two components. So, you could argue, that I broke the contract by not passing two child components to Toggle. That is all true.

What I want to show instead, is the fact that if you pass only one child component, then this.props.children is not an array anymore. this.props.children is the one component. Which explains the index out of bounds error.

Some information about dealing with this.props.children is available here.

Thanks for reading!

comments powered by Disqus