NativeRouter is a routing solution provided by React Router that is specifically designed for React Native applications. It allows developers to implement routing functionality using a declarative API similar to that of React Router DOM, but tailored for mobile environments.
This article explores into React Router’s NativeRouter component for managing navigation in React Native apps, addressing setup, routing components, screen transitions, and integration with other React Native libraries.
PrerequisitesFeatures- Overview of NativeRouter and its benefits
- Step-by-step implementation guide for setting up NativeRouter
- Example usage of routing components like Route and Switch
- Practical code examples and output screenshots
- Best practices and considerations for using NativeRouter in React Native apps
Steps to Create React AppStep 1: Setting Up the ProjectEnsure you have React Native CLI installed:
npx react-native init NativeRouterApp cd NativeRouterApp Step 2: Installing React Routernpm install react-router-native Project Structure Project Files Updated dependencies "dependencies": { "react": "17.0.2", "react-native": "0.64.3", "react-router-native": "^5.2.1" } Step 3: Write the code Example: To Illustrate native router using react router.
JavaScript
// App.js
import React from 'react';
import { NativeRouter, Route, Link } from 'react-router-native';
import HomeScreen from './screens/HomeScreen';
import AboutScreen from './screens/AboutScreen';
const App = () => {
return (
<NativeRouter>
<Route exact path="/" component={HomeScreen} />
<Route path="/about" component={AboutScreen} />
{/* Additional routes can be added here */}
</NativeRouter>
);
}
JavaScript
// screens/AboutScreen.js
import React from 'react';
import { View, Text } from 'react-native';
const AboutScreen = () => {
return (
<View>
<Text>Welcome to About Screen!</Text>
</View>
);
}
export default AboutScreen;
JavaScript
// screens/HomeScreen.js
import React from 'react';
import { View, Text, Button } from 'react-native';
import { Link } from 'react-router-native';
const HomeScreen = () => {
return (
<View>
<Text>Welcome to Home Screen!</Text>
<Link to="/about">
<Button title="Go to About Screen" />
</Link>
</View>
);
}
export default HomeScreen;
Step 4: Running the App
Run your React Native application:
npx react-native run-android Output:
 HomeScreen  AboutScreen
|