Navigation
React Navigation
The most popular library for navigation is React Navigation. In version 5 it offers the following 3 types of navigation:
- Drawer: Menu that comes out from left or right
- Tab: Either top or bottom tab navigation
- Stack: Transitions from one screen to the next and back to the previous screen
- Switch: Only ever show one screen at a time (no back action by default)
When you use version 4 then you have to add additional libraries for stack and tab navigation.
Installation see React Native Docs.
Nesting Navigation Layouts
We can easily compose our navigators like so:
// our imports
const switchNavigator = createSwitchNavigator({
loginFlow: createStackNavigator({
Signup: SignupScreen,
Signin: SigninScreen,
}),
mainFlow: createBottomTabNavigator({
blogFlow: createStackNavigator({
BlogList: BlogListScreen,
BlogDetail: BlogDetailsScreen
}),
BlogCreate: BlogCreateScreen
})
});
createAppContainer(switchNavigator);
Navigation Object
To be able to navigate you need the navigation
object. It get automatically passed as prop to each screen
that you have wired up. If you need it in a (distant) component and you don't want ot pass the prop all the way down
then you get access to the navigation
prop by wrapping your component-export with withNavigation
.
E.g.
import { TouchableOpacity } from "react-native";
import { withNavigation } from "react-navigation";
const SomeComponent = ({navigation}) => {
return (
<TouchableOpacity onPress={() => navigation.navigate('SomeScreen')}>
...
</TouchableOpacity>
)
};
export default withNavigation(SomeComponent);
Navigate with params
You can pass params to the navigate
-function, as so: navigation.navigate('ResultsShow', { id: item.id})}
.
And you access it via navigation.getParam
like that: const id = navigation.getParam('id');
.
NavigationEvents
You can use NavigationEvents
to trigger code in certain situations (it's like a hook, but as a component).
First, import via import { NavigationEvents } from 'react-navigation';
.
Second chose the appropriate hook and use it in your JSX, e.g. <NavigationEvents onWillBlur={ clearErrorMessage }/>
.
withNavigationFocus
If you want to run code once a screen gets the focus you can alternatively use withNavigationFocus
like so:
export default withNavigationFocus(MyScreen);
By doing so, your screen will get access to the prop isFocused
, e.g const MyScreen = ({ isFocused }) => {...}
.
This is useful when a component of the screen has to do something based on whether it is focused or not. The screen
can simply pass this prop down or use in a function call.