One day I was working on my React-Native project and got this weird error, “React.Children.only expected to receive a single React element child“. Everything seemed perfectly alright with the code but the compiler was complaining. After spending an hour, I was able to figure out the mistake. But first, let’s see the code.
Code Example
export default function App(){ return( <View> <Text>Tony Stark is Ironman</Text> <TouchableHighlight style={{width: '50px', height: '50px', backgroundColor: 'yellow'}} /> </View> ) }
In this code we have created a View
with 2 children – Text
and TouchableHighlight
. The Text will display a string and then there will be an area of size 50px X 50px of yellow background color. When this area is touched, a function will be called. This is correct then why did I get the error? We can have multiple children in a View. Why it’s complaining for a single child?
Actually, the error is not with View
but with TouchableHighlight
. According to React documentation –
TouchableHighlight must have one child (not zero or more than one). If you wish to have several child components, wrap them in a View.
In our code we have not provided any child to TouchableHighlight
. Even though we just want an area without any text or image or button, we still need to provide a child. And this can be done by adding a View
into it with all the required styling. The correct code will be –
export default function App(){ return( <View> <Text>Tony Stark is Ironman</Text> <TouchableHighlight> <View style={{width: '50px', height: '50px', backgroundColor: 'yellow'}} /> </TouchableHighlight> </View> ) }