I am trying to build a simple react-native application and facing the following issue in my code. If I remove the <Link> component and keep the <Text> component, error is going away. If I try to keep the <Link> component and remove the <Text> component, error comes back.
Can anyone please help me with this?
import * as React from "react";
import { View, Text } from "react-native";
import { Link } from "react-router-native";
function Home() {
return (
<View>
<Text>Welcome!</Text>
<Link to="/profile">Visit your profile</Link>
</View>
);
}
Error: React.Children.only expected to receive a single React element child.
CodePudding user response:
The react-router V6 docs say that <Link> renders a TouchableHighlight and it must have at least (and most) one child and also must be wrapped in a <View> element. Please change your implementation as follows.
import * as React from 'react';
import {View, Text} from 'react-native';
import {Link} from 'react-router-native';
function Home() {
return (
<View>
<Text>Welcome!</Text>
<Link to="/profile">
<Text>Visit your profile</Text>
</Link>
</View>
);
}
If you want to override default styling and behavior, please refer to the Props reference for TouchableHighlight.
CodePudding user response:
In v6 react-router, The <Link> should have exactly 1 element. But in your case, The text Visit, your and profile is being assumed as 3 text nodes.
To make it as one element, You can simply wrap it into <Text>. So the <Link> will have only one <Text> element but that has 3 text nodes inside which is not a problem to <Link>
function Home() {
return (
<View>
<Text>Welcome!</Text>
<Link to="/profile">
<Text>Visit your profile<Text>
</Link>
</View>
);
}
