Wednesday, March 15, 2023
HomeReactGetting Began with React Navigation v6 and TypeScript in React Native by...

Getting Began with React Navigation v6 and TypeScript in React Native by Aman Mittal


Getting Began with React Navigation v6 and TypeScript in React Native

Printed on Jun 11, 2022

•

14 min learn

•

cover_image

When you will have a fancy cellular software construction or many screens in your software, dealing with navigation can turn into tough. Nonetheless, with open-source libraries like React Navigation, the method of implementing navigation patterns does turn into simpler.

React Navigation library is without doubt one of the most used navigation libraries in React Native ecosystem. It’s written in TypeScript, and you’ll create React parts and apply any navigation patterns from Stack, Tab, and Drawer.

On this tutorial, let’s take a look at how one can arrange and use React Navigation and TypeScript collectively in a React Native app. One cool benefit that TypeScript supplies is sort checking for route names and route parameters.

Pre-requisites

🔗

If you will code alongside, ensure you have already put in the next:

  • Nodejs (>=12.x.x) with npm/yarn put in
  • expo-cli
  • Entry to an actual machine or an iOS simulator or an Android Emulator with the intention to run your code instance

The supply code used on this tutorial is accessible at this GitHub repository.

Making a React Native venture with expo-cli

🔗

Earlier than diving deep into configuring TypeScript with React Navigation, allow us to create an instance app that makes use of React Navigation to navigate between completely different screens. This instance display can even have instance screens.

You’ll be able to skip this part if you’re already aware of Stack and Tab navigators in React Navigation.

Open the terminal and run the next command to create a brand new React Native app. When requested to “select a template”, choose clean (TypeScript). This template creates a React Native venture with TypeScript already configured. Sufficient for us to get began.

After navigating contained in the venture listing, run the next command to put in React Navigation libraries and its packages within the terminal window.

yarn add @react-navigation/native @react-navigation/bottom-tabs @react-navigation/native-stack && expo set up react-native-screens react-native-safe-area-context

The above command will set up packages for implementing Stack and Tabs navigators. Within the instance app, we are going to use each of those patterns.

Including a stack navigator

🔗

React Navigation’s stack navigator permits your app to transition between screens and handle navigation historical past. The stack navigator you’ll implement on this part will enable the app consumer to navigate from one display to a different.

Begin by making a src/ listing that may comprise the display and navigation associated code information.

The following step within the instance app is to create mock screens. Create a screens/ listing inside src/. Inside this listing, let’s create 4 part information:

  • HomeScreen.tsx
  • DetailsScreen.tsx

The HomeScreen part shows an inventory of characters from the Star Wars API. On urgent any merchandise from the listing, the app consumer will be capable of navigate to the DetailsScreen the place they’ll view the small print of every character.

Add the next code snippet to the HomeScreen.tsx:

1import { StyleSheet, View, Textual content, Pressable, FlatList } from 'react-native';

2import { useNavigation } from '@react-navigation/native';

3

4const DATA = [

5 {

6 id: 1,

7 name: 'Luke Skywalker',

8 birth_year: '19BBY'

9 },

10 {

11 id: 2,

12 name: 'C-3PO',

13 birth_year: '112BBY'

14 },

15 {

16 id: 3,

17 name: 'R2-D2',

18 birth_year: '33BBY'

19 },

20 {

21 id: 4,

22 name: 'Darth Vader',

23 birth_year: '41.9BBY'

24 },

25 {

26 id: 5,

27 name: 'Leia Organa',

28 birth_year: '19BBY'

29 }

30];

31

32const HomeScreen = () => {

33 const navigation = useNavigation();

34

35 const renderListItems = ({ merchandise }) => {

36 return (

37 <Pressable

38 onPress={() =>

39 navigation.navigate('Particulars', {

40 identify: merchandise.identify,

41 birthYear: merchandise.birth_year

42 })

43 }

44 >

45 <Textual content

46 model={{ fontSize: 18, paddingHorizontal: 12, paddingVertical: 12 }}

47 >

48 {merchandise.identify}

49 </Textual content>

50 <View

51 model={{

52 borderWidth: StyleSheet.hairlineWidth,

53 borderColor: '#ccc'

54 }}

55 />

56 </Pressable>

57 );

58 };

59

60 return (

61 <View model={{ flex: 1, paddingTop: 10 }}>

62 <FlatList information={DATA} renderItem={renderListItems} />

63 </View>

64 );

65};

66

67export default HomeScreen;

Within the above code snippet, observe that the onPress prop on the Pressable part is used to go the identify and birthYear of the character to the Particulars display as route parameters.

Add the next code snippet to the DetailsScreen.tsx:

1import { View, Textual content } from 'react-native';

2import { useRoute } from '@react-navigation/native';

3

4const DetailScreen = () => {

5 const route = useRoute();

6 const { identify, birthYear } = route.params;

7

8 return (

9 <View model={{ flex: 1, paddingTop: 12, paddingHorizontal: 10 }}>

10 <Textual content model={{ fontSize: 18, paddingBottom: 12 }}>Identify: {identify}</Textual content>

11 <Textual content model={{ fontSize: 18 }}>Beginning 12 months: {birthYear}</Textual content>

12 </View>

13 );

14};

15

16export default DetailScreen;

Within the above code snippet, discover that the route.params is used to learn the parameters handed from the HomeScreen.

After organising the screens, create the navigation/ listing contained in the src/ and inside it, add two information:

  • index.tsx: to maintain the Root Navigator configuration
  • HomeStack.tsx: to create a Stack Navigator for Residence and Particulars screens

Contained in the HomeStack.tsx file, add the next code snippet:

1import * as React from 'react';

2import { createNativeStackNavigator } from '@react-navigation/native-stack';

3

4import HomeScreen from '../screens/HomeScreen';

5import DetailsScreen from '../screens/DetailsScreen';

6

7const HomeStack = createNativeStackNavigator();

8

9const HomeStackNavigator = () => {

10 return (

11 <HomeStack.Navigator>

12 <HomeStack.Display identify="Residence" part={HomeScreen} />

13 <HomeStack.Display identify="Particulars" part={DetailsScreen} />

14 </HomeStack.Navigator>

15 );

16};

17

18export default HomeStackNavigator;

Within the above code snippet, discover that the identify prop on the HomeStack.Display part is used to outline the route identify. For instance, the DetailsScreen has the route identify outlined as Particulars. Any time you navigate the Particulars display, the route identify is used to determine the display both within the navigation.navigate() or navigation.push() technique.

Subsequent, add the next code snippet to the index.tsx file:

1import * as React from 'react';

2import { NavigationContainer } from '@react-navigation/native';

3

4import HomeStackNavigator from './HomeStack';

5

6const RootNavigator = () => {

7 return (

8 <NavigationContainer>

9 <HomeStackNavigator />

10 </NavigationContainer>

11 );

12};

13

14export default RootNavigator;

Lastly, modify the App.tsx file to incorporate the RootNavigator part:

1import { StatusBar } from 'expo-status-bar';

2

3import RootNavigator from './src/navigation';

4

5export default perform App() {

6 return (

7 <>

8 <RootNavigator />

9 <StatusBar model="auto" />

10 </>

11 );

12}

The HomeStack navigator configuration is completed. Subsequent, run any of the next instructions to see the navigator in motion:

expo begin --ios

expo begin --android

Right here is the output you’re going to get after this step:

ss1

Including sort checking for stack navigator

🔗

To sort verify route identify and parameters in each the HomeStack and RootStack navigators, it’s good to create sort mappings for every route identify and params.

Begin by creating a brand new file known as sorts.ts contained in the src/navigation/ listing. This file will comprise mappings for all route names and route params. All through this tutorial, it’s used to outline sorts for every sort of navigator.

Contained in the file sorts.ts, outline the categories for the route names: Residence and Particulars.

1export sort HomeStackNavigatorParamList = {

2 Residence: undefined;

3 Particulars: {

4 identify: string;

5 birthYear: string;

6 };

7};

A route identify that does not have any parameters being handed is specified with undefined. So, for instance, within the above snippet, the Residence route identify would not have any parameters being handed to it.

The Particulars route receives two parameters from the HomeScreen. Because of this the mapping object incorporates two properties within the above snippet.

After creating the mappings, you should let the stack navigator find out about them. Return to the HomeStack.tsx file and inside it, import HomeStackNavigatorParamList. It’s handed as a generic to the createNativeStackNavigator perform.

1

2import { HomeStackNavigatorParamList } from './sorts';

3

4const HomeStack = createNativeStackNavigator<HomeStackNavigatorParamList>();

5

6

Testing sort checking and IntelliSense

🔗

All of the configurations within the earlier part will allow sort checking for the HomeStack navigator. For instance, within the HomeStack.tsx file, change the identify of the Particulars to Element.

1<HomeStack.Display identify="Element" part={DetailsScreen} />

After the modification, you will note a purple squiggly line seems on the identify prop.

ss3

For those who hover over the identify prop, it can present an identical error message like the next:

ss4

The HomeStack navigator expects a HomeStackNavigatorParamList sort with both Residence or Particulars.

One other benefit of sort checking is that it supplies intelliSense for navigator props (relying on which IDE or Code editor you might be utilizing). For giant functions the place there are lots of screens, this helps. You should not have to recollect every route params for each display.

Including sort checks for screens

🔗

On this part, let’s discover ways to add sort checking for the Residence display. It’s the display the place an app consumer will work together with a button to navigate to the Particulars display.

So as to add sort checking for a display, step one is to make use of a generic sort to outline sorts for the person screens. Every navigator sample in React Navigation library exposes its personal generic sort. For instance, NativeStackNavigationProp is used for @react-navigation/native-stack. Import that within the sorts.ts file.

1import sort { NativeStackNavigationProp } from '@react-navigation/native-stack';

2

3export sort HomeStackNavigatorParamList = {

4 Residence: undefined;

5 Particulars: {

6 identify: string;

7 birthYear: string;

8 };

9};

10

11export sort HomeScreenNavigationProp = NativeStackNavigationProp<

12 HomeStackNavigatorParamList,

13 'Particulars'

14>;

The NativeStackNavigationProp settle for two parameters. The primary is the kind that maps the route names and their params. Therefore, the navigator itself. The second is the identify of the display as a string that matches the route identify from the primary parameter. Within the above code snippet, the primary parameter is HomeStackNavigatorParamList, and the second parmater, on this case, can solely be Particulars.

The second parameter of NativeStackNavigationProp represents that the Residence display will get solely the described route identify as a risk that the Residence display can navigate to. If the second parameter will not be outlined, then the Residence display will get all of the route names from the HomeStack navigator as potentialities that it might probably navigate to.

Now, open the HomeScreen file, import the HomeScreeProps sort, and use it to annotate the useNavigation hook.

1

2

3

4import { HomeScreenNavigationProp } from '../navigation/sorts';

5

6

7const HomeScreen = () => {

8 const navigation = useNavigation<HomeScreenNavigationProp>();

9

10

11};

In case you are utilizing the navigation prop straight on the practical part, you possibly can go the HomeScreenNavigationProp sort to the practical part.

1perform HomeScreen({ navigation }: HomeScreenNavigationProp) {

2

3}

In case you are utilizing @react-navigation/stack, you should utilize StackScreenProps as a substitute of StackNavigationProp.

Including sort checks for route params

🔗

So as to add sort checking for a display that receives route params (for instance, within the instance app Particulars display receives two route params), it’s good to import the RouteProp from @react-navigation/native.

After importing it, create a sort for the Particulars display utilizing the HomeStackNavigatorParamList as the primary parameter and the route identify of the Particulars display because the second parameter to the RouteProp.

1

2import sort { RouteProp } from '@react-navigation/native';

3

4export sort DetailsScreenRouteProp = RouteProp<

5 HomeStackNavigatorParamList,

6 'Particulars'

7>;

8

9

Open the DetailsScreen file, import the DetailsScreenRouteProp sort, and use it to annotate the useRoute hook.

1

2import { DetailsScreenRouteProp } from '../navigation/sorts';

3

4

5

6const DetailScreen = () => {

7 const route = useRoute<DetailsScreenRouteProp>();

8

9

10};

Including a backside navigator

🔗

Let’s proceed the saga of including sort checks to the app screens by including a Backside Tab Navigator to the instance app. We’ve got already put in the underside tabs bundle when creating the instance app.

Let’s add two extra screens to the src/screens/ listing. Inside it, create a brand new file FeedScreen.tsx and add the next code snippet:

1import { View, Textual content } from 'react-native';

2

3const FeedScreen = () => {

4 return (

5 <View model={{ flex: 1, paddingTop: 12, paddingHorizontal: 10 }}>

6 <Textual content model={{ fontSize: 18 }}>Feed Display</Textual content>

7 </View>

8 );

9};

10

11export default FeedScreen;

Create one other new file known as SettingsScreen.tsx and add the next code snippet:

1import { View, Textual content } from 'react-native';

2

3const SettingsScreen = () => {

4 return (

5 <View model={{ flex: 1, paddingTop: 12, paddingHorizontal: 10 }}>

6 <Textual content model={{ fontSize: 18 }}>Settings Display</Textual content>

7 </View>

8 );

9};

10

11export default SettingsScreen;

Subsequent, add the kind verify mapping objects for the underside tab navigator within the src/navigation/sorts.ts file. The identify of the navigator is BottomTabNavigatorParamList.

The underside tab navigator will comprise the Residence display as its first tab. The second tab would be the Feed display. The third tab would be the Settings display. You’ll be able to specify HomeStackNavigatorParamList as the worth for the Residence key.

1export sort BottomTabNavigatorParamList = {

2 Residence: HomeStackNavigatorParamList;

3 Feed: undefined;

4 Settings: undefined;

5};

Contained in the src/navigation/ listing, add a brand new file known as Tabs.tsx with the next code snippet:

1import * as React from 'react';

2import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

3

4import { BottomTabNavigatorParamList } from './sorts';

5import HomeStackNavigator from './HomeStack';

6import FeedScreen from '../screens/FeedScreen';

7import SettingsScreen from '../screens/SettingsScreen';

8

9const Tab = createBottomTabNavigator<BottomTabNavigatorParamList>();

10

11const BottomTabs = () => {

12 return (

13 <Tab.Navigator>

14 <Tab.Display

15 identify="HomeStack"

16 part={HomeStackNavigator}

17 choices={{ headerShown: false }}

18 />

19 <Tab.Display identify="Feed" part={FeedScreen} />

20 <Tab.Display identify="Settings" part={SettingsScreen} />

21 </Tab.Navigator>

22 );

23};

24

25export default BottomTabs;

Annotating sorts for the underside tab navigator with BottomTabNavigatorParamList will add sort checks for every display within the tab navigator.

Let’s additionally modify the src/navigation/index.tsx file to exchange the earlier HomeStack by importing the BottomTabs part and rendering it.

1

2import BottomTabs from './Tabs';

3

4const RootNavigator = () => {

5 return (

6 <NavigationContainer>

7 <BottomTabs />

8 </NavigationContainer>

9 );

10};

11

12export default RootNavigator;

Right here is the output you get after this step:

ss5

Composing nested navigator sorts

🔗

Within the present state of the instance app, you’ll discover that the HomeStack navigator is now nested inside the underside tab navigator.

Let’s assume, for some motive, you wish to present a button for the app consumer to navigate from the Residence display to the Feed display. That is doable since each of those screens share the identical father or mother navigator.

Add a button above the FlatList within the HomeScreen.tsx file that permits an app consumer to navigate to the Feed display as proven under:

1return (

2 <View model={{ flex: 1, paddingTop: 10 }}>

3 <Pressable

4 onPress={() => navigation.navigate('Feed')}

5 model={{

6 padding: 8,

7 borderWidth: 1,

8 borderRadius: 4,

9 borderColor: 'purple',

10 margin: 12,

11 alignItems: 'heart'

12 }}

13 >

14 <Textual content model={{ fontSize: 16, fontWeight: '600' }}>Go to Feed display</Textual content>

15 </Pressable>

16 <FlatList information={DATA} renderItem={renderListItems} />

17 </View>

18);

Right here is how the button appears to be like on the Residence display:

ss6

For those who look carefully on the JSX simply added, a purple squiggly line has appeared beneath Feed.

ss7

The error states that the Feed display will not be a part of the HomeScreenNavigationProp, which is true as a result of the Feed display will not be a part of the param listing we outlined for the Residence stack navigator within the src/navigation/sorts.tsx file.

React Navigation library exposes the CompositeNavigationProp sort that permits annotating the navigation prop when nesting navigators. It takes two parameters. The primary parameter is the first navigator, on this case, the Residence Stack navigator itself. The second parameter is the kind of a father or mother navigator or every other supply of secondary navigation. On this case, will probably be the underside tab navigator.

Modify the kind HomeScreenNavigationProp as proven under:

1import sort {

2 CompositeNavigationProp,

3 RouteProp

4} from '@react-navigation/native';

5

6

7export sort HomeScreenNavigationProp = CompositeNavigationProp<

8 NativeStackNavigationProp<HomeStackNavigatorParamList, 'Particulars'>,

9 BottomTabNavigationProp<BottomTabNavigatorParamList, 'Feed'>

10>;

11

12

For those who return to the HomeScreen.tsx file, you will note the purple squiggly gone.

Conclusion

🔗

On this tutorial, we mentioned learn how to add sort checks to the app screens and learn how to add sort checks to the React Navigation navigators. Utilizing sort checks and annotating navigators is an effective way to make your app extra sturdy and maintainable when utilizing TypeScript with React Navigation.

I like to recommend you to verify the entire sort checking with TypeScript official documentation right here offered by React Navigation library maintainers.


I am a software program developer and a technical author. On this weblog, I write about Technical writing, Node.js, React Native and Expo.

Presently, working at Expo. Beforehand, I’ve labored as a Developer Advocate, and Senior Content material Developer with corporations like Draftbit, Vercel and Crowdbotics.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments