React Native Day 12 Navigation

Navigation Controller works like stack data structure. Let’s say I have three screen and I want to navigate from A -> B -> C. In this case A will be at the bottom of the stack, B will be stacked on top of A and C will be at the top of B.

In case you want are on C and we popped C out from stack (obviously cleared from memory), we will remain with B and A only.

In case you want are on C and we want to reach A, we have to pop both C and B together to reach on A. Memory for both C and B will be deallocated.

When we open a new screen it is “PUSH”, always create new memory area.

When we resume already existing screen known as “POP”. Always memory of “POPPED” screens will be released from memory.

Above description was for layman language where I have used word screen. For Android it will be Activity object and for iOS it will be View Controller Object.

Let’s create a new react native project” by typing in terminal:

Auto generated code of App.js looks like below:

 

After that run it and it should look like below:

Great let’s start Navigation logic:

Open new terminal window and run:

We are installing react-navigation latest version:

Now in App.js:

Then let’s create navigation component, MainNavigator which looks like below code:

createStackNavigator
Provides a way for your app to transition between screens where each new screen is placed on top of a stack.createStackNavigator is a function that returns a React component. It takes a route configuration object and, optionally, an options object. Because the createStackNavigator function returns a React component, we can export it directly from App.js to be used as our App’s root component.

createAppContainer returns react component, it is root of the app and takes care of navigation logic for iOS and Android.

Let’s create home screen:

Two Most important part of this code are:

The title to be shown on top of Home screen is ‘Welcome’

AND

Here we are saying navigate to ‘ProfileScreen’ with parameters as itemId : 86 and otherParam : ‘anything you want here’

let’s create detail screen:

Two Most important part of this code are:

AND

See how we have accessed itemId and otherParam.

The complete code of App.js is below:

Run it and you should see below output:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.