I recently published an article on how to set up a basic navigator using the react-navigation 5.x library. React-Navigation is a fantastic way to add navigtion to a React-Native applicaiton. It allows us to safely travel between screens and keep a history if where we were before. However, in any application there will be a time when we will need to also pass information form one screen to the next. This becomes especially important when that information refers to information either from state, or from an API. In this article I will be discussing how to pass information using routes.

A quick caveat: To speed things up I am going to use the code from my previous blog post and I am not going to worry about state management at this time.

Snipets from “Using React Navigation 5x

// App.js

import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import HomeScreen from './src/screens/HomeScreen
import FirstScreen from './src/screens/FirstScreen'
import SecondScreen from './src/screens/SecondScreen
const Stack = createStackNavigator()
export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen 
          component={HomeScreen}
          name="Home"
        />
        <Stack.Screen 
          component={FirstScreen}
          name="First"
        />
        <Stack.Screen 
          component={SecondScreen}
          name="Second"
        />
      </Stack.Navigator>
    </NavigationContainer>
  )
}
...
//HomeScreen
import React from 'react'
import { View, Button } from 'react-native'
const HomeScreen = ({navigation}) => {
  return (
    <View>
      <Button
        title='First'
        onPress={() => navigation.navigate("First")}
      />
      <Button
        title='Second'
        onPress={() => navigation.navigate("Second")}
      />
    </View>
  )
}
export default HomeScreen
...
// FirstScreen
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
const FirstScreen = () => {
  return (
    <View>
      <Text> First Screen </Text>
    </View>
  )
}export default FirstScreenconst styles = StyleSheet.create({})
...
//Second Screen
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'const 
SecondScreen = () => {
  return (
    <View>
      <Text> Second Screen </Text>
    </View>
  )
}
export default SecondScreenconst styles = StyleSheet.create({})

#mobile-app-development #react-native #code-newbie #react #navigation

Passing Params With React Navigation
3.05 GEEK