I have the following render method in my React Native code:
render() {
const {height, width} = Dimensions.get('window');
return (
<View style={styles.container}>
<Image
style={{
height:height,
width:width,
}}
source={require('image!foo')}
resizeMode='cover'
/>
<TouchableHighlight style={styles.button}/>
</View>
);
}
It gives me a
React.Children.only expected to receive a single React element child
error. If I remove the TouchableHighlight
component, it works fine. On the other hand, if I remove the Image component, it still gives that error. I can't see why it would be giving this error, and <View>
should be able to have more than one component inside it for rendering.
Any ideas?
This question is related to
react-native
I had this same error, even when I only had one child under the TouchableHighlight
. The issue was that I had a few others commented out but incorrectly. Make sure you are commenting out appropriately: http://wesbos.com/react-jsx-comments/
Yes, indeed you need to have one child inside your <TouchableHighlight>
.
And, If you don't want to pollute your file with Views
you can use React Fragments to achieve the same.
<TouchableWithoutFeedback>
<React.Fragment>
...
</React.Fragment>
</TouchableWithoutFeedback>
or even better there is a short syntax for React Fragments. So the above code can be written as below:
<TouchableWithoutFeedback>
<>
...
</>
</TouchableWithoutFeedback>
The <TouchableHighlight>
element is the source of the error. The <TouchableHighlight>
element must have a child element.
Try running the code like this:
render() {
const {height, width} = Dimensions.get('window');
return (
<View style={styles.container}>
<Image
style={{
height:height,
width:width,
}}
source={require('image!foo')}
resizeMode='cover'
/>
<TouchableHighlight style={styles.button}>
<Text> This text is the target to be highlighted </Text>
</TouchableHighlight>
</View>
);
}
Usually it happen in TochableHighlight. Anyway error mean that you must used single element inside the whatever component.
Solution : You can use single view inside parent and anything can be used inside that View. See the attached picture
<TouchableHighlight>
element can have only one child inside just after TouchableWithoutFeedback
or <TouchableHighlight>
insert a <View>
this way you won't get this error. why is that then @Pedram answer or other answers explains enough.
In my case, I just had to put the element one line down:
This throws an error:
export function DismissKeyboard(props: IProps) {
return <TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}> {props.children}
</TouchableWithoutFeedback>;
}
_x000D_
While this does not throw an error:
export function DismissKeyboard(props: IProps) {
return <TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}>
{props.children}
</TouchableWithoutFeedback>;
}
_x000D_
Source: Stackoverflow.com