Implementing navigation in React Native
React Native provides a number of navigation options for building mobile apps. You can use the built-in Navigator
component or a third-party navigation library like react-navigation
. In this example, we will use react-navigation
to implement navigation in a React Native app.
Here's how to set up a basic navigation structure using react-navigation
:
- Install the
react-navigation
library:
npm install react-navigation
- Create a stack navigator:
import React from 'react';
import { View, Button, Text } from 'react-native';
import { createStackNavigator } from 'react-navigation-stack';
const HomeScreen = ({ navigation }) => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
const DetailsScreen = () => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
const RootStack = createStackNavigator({
Home: {
screen: HomeScreen,
},
Details: {
screen: DetailsScreen,
},
});
export default RootStack;
In this example, we have created a stack navigator with two screens: HomeScreen
and DetailsScreen
. The HomeScreen
component contains a button that will navigate to the DetailsScreen
when pressed.
- Render the navigator:
import React from 'react';
import RootStack from './RootStack';
const App = () => (
<RootStack />
);
export default App;
In this example, we have imported the stack navigator created in step 2 and rendered it in the App
component.
With these steps, you can create a basic navigation structure in your React Native app using react-navigation
. You can also customize the navigation options and add additional screens to your navigator as needed.
Leave a Comment