React Native: Fix for "onlyChild Must Be Passed a Children With Exactly One Child"

If you’ve run into onlyChild must be passed a children with exactly one child in React Native there’s a simple fix.

All of the “Touchable” components in React Native do an onlyChild check on their children, which throws an error unless there’s exactly one child.

1
2
3
4
return (
  <TouchableHighlight>
  </TouchableHighlight>
); // Error: onlyChild must be passed a children with exactly one child

Adding a child to the TouchableHighlight will fix the error

1
2
3
4
5
return (
  <TouchableHighlight>
      <Text>foo</Text>
  </TouchableHighlight>
); // OK

But adding multiple children will also cause an error

1
2
3
4
5
6
return (
  <TouchableHighlight>
      <Text>foo</Text>
      <Text>bar</Text>
  </TouchableHighlight>
); // Error: onlyChild must be passed a children with exactly one child

A quick search through the React Native code reveals the components that verify onlyChild:

  • TouchableBounce
  • TouchableHighlight
  • TouchableOpacity
  • TouchableWithFeedback

Hopefully React Native can eventually provide a better message for this issue, but until then, at least this blog post should pop up when you Google the error.

I am now accepting new clients for part-time consulting and software development projects. Learn more

I haven't configured comments for this blog, but if you want to get in touch, you can find me on Twitter