How can I create dynamic routes/ screens with React Native?

Viewed 1244

I want to create dynamic routes similar to the way you can with react-router using the slash colon as so:

<Route exact path="/user/:_id" component={UserPage} />

How does this work with react native if I want to open a page specif to a link?

const Item = ({ title }) => (
  <View style={styles.item}>
    <Button
      onPress={() => {
        alert(`You tapped ${title}`);
      }}
      title={title}
    >
      <Text style={styles.title}>{title}</Text>
    </Button>
  </View>
);

const MainPage = () => (
  <SafeAreaView style={styles.container}>
    <SectionList
      sections={DATA}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  </SafeAreaView>
);


export default MainPage;
function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
        <Stack.Screen name="MainPage" component={MainPage} />
        <Stack.Screen name="MediaScreen" component={MediaScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

I want the Item onPress to go to its own page/screen

2 Answers

As for as I know react native navigation doesnt allow url params, you have to pass parameters when you call the navigate function.

const Item = ({ title, navigation }) => (
  <View style={styles.item}>
    <Button
      onPress={() => {
        alert(`You tapped ${title}`);
        navigation.navigate('Details', { _id })
      }}
      title={title}
    >
      <Text style={styles.title}>{title}</Text>
    </Button>
  </View>
);

const MainPage = ({ navigation }) => (
  <SafeAreaView style={styles.container}>
    <SectionList
      sections={DATA}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} navigation={navigation}/>}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  </SafeAreaView>
);


export default MainPage;

Then in Details it will have a route parameter which you can get _id from route.params._id

const Details = ({ navigation, route }) => {
    const [_id] = useState(route.params._id);
    return (
        <></>
    )
};

With react-navigation you can pass parameters in two ways:

1 - Pass params to a route by putting them in an object as a second parameter to the navigation.navigate function: navigation.navigate('RouteName', { /* params go here */ })

2 - Read the params in your screen component: route.params.

Full documentation https://reactnavigation.org/docs/params

Related