Home > Net >  Switching Between Screens with React Native Navigation and importing JS
Switching Between Screens with React Native Navigation and importing JS

Time:12-23

I'm struggling to figure out why my code doesn't work. I keep reading the tutorials and nothing helps. How can I switch between screens and have the screens in different JS files (as components)?

Currently, my code works for the first screen, but when I click on the button nothing shows up.

Please see the codes below:

App.js

import * as React from 'react';
import {Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import TestScreen from './components/Test';


//HOME SCREEN
function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Test"
        onPress={() => navigation.navigate('Test',{myParam: '03',})}
      />
    </View>
  );
}

const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Test" component={TestScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Test.js

import React, { Component } from "react";
import { Text, View } from "react-native";

class Test extends Component {
    render() {
   const { navigation } = this.props;
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Test Screen</Text>
        <Button
          title="Test"
          onPress={() => navigation.navigate('Home')}
        />
      </View>

    );
  }
}   


export default Test;

CodePudding user response:

First you have to import useNavigation in Test.js file.

Like this:

import { useNavigation } from "@react-navigation/core";

Then you have to use it and save it in a variable like:

const navigation = useNavigation();

Now use:

onPress={() => navigation.navigate('Home')};

This will navigate to the the other Screen.

Make sure you install every library you use in your project using npm or yarn.

CodePudding user response:

It seems it was a very simple issue and I figured it out myself. The code was missing 'button' in the import from react-native. It's not the first this happens to me. I use Visual Studio Code, which shows different colours for missing things, but it seems that doesn't work for the JSX elements.

  • Related