Add navigation to an existing React-Native app built using Expo.
We’ll be using the React Navigation package.
Install React-Navigation.
$ npm install --save react-navigation
To connect the navigation system across all of the different screens/components, the root dom element needs to be setup with a list of all our components. Then we can link back and forth between them.
import { createStackNavigator } from 'react-navigation';
const Root = createStackNavigator(
{
ScreenA: ComponentForScreenA,
ScreenB: ComponentForScreenB,
ScreenC: ComponentForScreenC
},
{
initialRouteName: 'ScreenA',
navigationOptions: {
headerStyle: {
elevation: 1,
backgroundColor: '#fff',
height: 30,
}
}
}
);
export default class App extends React.Component {
render() {
return <Root />;
}
}
Note: Whichever component you put for ‘initialRouteName’ will be the component loaded when the app starts. During development I typically make this whichever page I am working on.
Inside each component that is a link in the menu we need to add code to handle the ‘Next’ and ‘Back’ links and the title of the current page.
static navigationOptions = ({navigation}) => {
return {
headerLeft: (
<HeaderBack
navigation={navigation}
text={"Back"}
nav_link={"ScreenA"}
/>
),
headerTitle: (
<HeaderTitle text={"This Page's Title"} />
),
headerRight: (
<HeaderNext
navigation={navigation}
text={"Next"}
nav_link={"ScreenC"}
/>
),
};
}
We need 2 components to handle our ‘Back’ and ‘Next’ links in the navigation menu. You can pass variables through these links to manage state for your app. We’ll talk more about that in the next step.
<TouchableOpacity
activeOpacity={.6}
onPress={() => this.props.navigation.navigate(this.props.nav_link, {
someVariable: this.props.someVariable,
anotherVariable: this.props.anotherVariable
})}
>
{
this.props.text ? (
<View>
<Text>
{this.props.text}
</Text>
</View>
) : null
}
</TouchableOpacity>
This is how to link to another component and also pass parameters to that component.
<View>
<TouchableOpacity
activeOpacity={.6}
onPress={() => this.props.navigation.navigate("ComponentWeAreLinkingTo", {
variableA: 'textInformation',
variableB: someVariable
})}
>
<Text>This is a link</Text>
</TouchableOpacity>
</View>
In the receiving component you access the parameters passed to you like so…
componentDidMount() {
this.handleIncomingParameter();
}
handleIncomingParameter() {
const variableA = this.props.navigation.getParam('variableA');
this.setState({
variableA: variableA
});
}