today is tomorrow's past

today is tomorrow's past

I help people create remarkable things. Focus on the customer and quality. Opinions are my own. Photography is my other passion.

1-Minute Read

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


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 (

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

Recent Posts



Always something to think about