Integrate StackNavigator with TabNavigator - reactjs

How do I combine StackNavigator and TabNavigator?
My following code works:
index.android.js :
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
import { StackNavigator,TabNavigator } from 'react-navigation';
import TestComp1 from './src/components/TestComp1'
import TestComp2 from './src/components/TestComp2'
import TestComp3 from './src/components/TestComp3'
import TestComp4 from './src/components/TestComp4'
import TestComp5 from './src/components/TestComp5'
export default class myApp extends Component {
render() {
return (
<MyApp />
);
}
}
const MyApp = StackNavigator({
TestComp1: {screen:TestComp1},
TestComp2: {screen:TestComp2}
});
const Tabs = TabNavigator({
TestComp3: {screen:TestComp3},
TestComp4: {screen:TestComp4}
TestComp5: {screen:TestComp5}
});
AppRegistry.registerComponent('myApp', () => myApp);
This works only for StackNavigator. I want to keep the existing navigation and integrate TabNavigation. Now in TestComp1 if I do the following:
TestComp1 :
import { StackNavigator, TabNavigator } from 'react-navigation';
import { FooterTabs } from './routes/FooterTabs';
export default class HomePage extends Component {
static navigationOptions = {
header: null
};
render() {
return(
<View style={styles.container}>
<View style={styles.mainContent}>
<Button
onPress={() => this.props.navigation.navigate('TestComp1', {name: 'Lucy'})}
title="NewPage"
/>
<FooterTabs /> //Page shows all StackNavigator screens if I add this
</View>
</View>
)
}
}
And the FooterTabs:
import { StackNavigator, TabNavigator } from 'react-navigation';
import TestComp3 from '../TestComp3';
import TestComp4 from '../TestComp4';
import TestComp5 from '../TestComp5';
export const FooterTabs = TabNavigator({
Tab1: {
screen: TestComp3
},
Tab2: {
screen: TestComp4
},
Tab3: {
screen: TestComp5
},
})
The FooterTabs is shown but TestComp1 and TestComp2 are also shown everything below one another. How do I fix this? Thanks.
UPDATE 1:
UPDATE 2:
const Tabs = TabNavigator({
TestComp3: {screen:TestComp1},
TestComp4: {
screen:TestComp4,
navigationOptions: ({ navigation }) => ({
title: "TestComp4",
tabBarIcon: ({ tintColor }) => <MaterialIcons name="accessibility" size={20}/>
})
}
UPDATE 3
I added another const for DrawerNavigator and configured it like this:
const Drawer = DrawerNavigator({
First:{
screen: DrawerScreen1
},
Second:{
screen: DrawerScreen2
}
},{
initialRouteName:'First',
drawerPosition: 'left'
});
And included in the app:
const MyApp = StackNavigator({
TestComp1: {screen:TestComp1},
TestComp2: {screen:TestComp2},
Tabs: {
screen: Tabs
},
Drawer: {
screen: Drawer
},
}, {
initialRouteName: "Tabs"
});
I'm calling it :
<Button
onPress={() => this.props.navigation.navigate('DrawerOpen')}
title="Show Drawer"
/>
OnPress of this button the DrawerScreen1 is called but as a component, it does not show as a drawer from the left. What am I missing?

You can try this:
const Tabs = TabNavigator({
TestComp3: {screen:TestComp3},
TestComp4: {screen:TestComp4}
TestComp5: {screen:TestComp5}
});
const MyApp = StackNavigator({
TestComp1: {screen:TestComp1},
TestComp2: {screen:TestComp2},
Tabs: {
screen: Tabs
}
}, {
initialRouteName: "Tabs"
});
and remove <FooterTabs /> from TestComp1

Let's see now. What you need is first a StackNavigator then inside one of the screens of the StackNavigator you need a TabNavigator. Right?
The answer to this would be the following:
For your index.android.js:
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
import { StackNavigator } from 'react-navigation';
import TestComp1 from './src/components/TestComp1'
import TestComp2 from './src/components/TestComp2'
// Don't need to export default here since this is the root component
// that is registered with AppRegistry and we don't need to import it anywhere.
class myApp extends Component {
render() {
return (
<MyApp />
);
}
}
// Notice that these two screens will consist the navigation stack.
// Assume, TestComp1 contains our Tabbed layout.
const MyApp = StackNavigator({
TestComp1: { screen:TestComp1 }, // This screen will have tabs.
TestComp2: { screen:TestComp2 }
});
AppRegistry.registerComponent('myApp', () => myApp);
Let's now move on to your TestComp1, which is the screen that has your tabs.
TestComp1:
// ... all imports here.
// This should be your first tab.
class Home extends Component {
static navigationOptions = {
// Label for your tab. Can also place a tab icon here.
tabBarLabel: 'Home',
};
render() {
return(
<View style={styles.container}>
<View style={styles.mainContent}>
// This will change your tab to 'Profile'.
<Button
onPress={() => this.props.navigation.navigate('Profile', {name: 'Lucy'})}
title="NewPage"
/>
</View>
</View>
)
}
}
// This can be your second tab and so on.
class Profile extends Component {
static navigationOptions = {
// Label for your tab.
tabBarLabel: 'Profile',
};
render() {
return (
<Text>This is the profile Tab.<Text>
);
}
}
export default TabNavigator({
Home: {
screen: Home,
},
Profile: {
screen: Profile,
},
}, {
// This will get the tabs to show their labels/icons at the bottom.
tabBarPosition: 'bottom',
animationEnabled: true,
tabBarOptions: {
activeTintColor: '#e91e63',
},
});
So essentially, your TestComp1 has two components (Home and Profile) inside it which are both parts of TabNavigator so they'll act as tabs. (You don't need to worry about a separate footer component as ReactNavigation places that automatically using your component's navigationOptions) We'll be exporting this TabNavigator instance that we'll use as an import to index.android.js and we'll place this import inside our StackNavigator as a screen of the app.
This way you've incorporated Tabs as well as StackNavigator inside your RN app. Also, tabBarPosition: 'bottom' places your tabs at the bottom.
You also no longer to maintain a separate FooterTabs component as you can see.
Read up the docs if you need more clarity or fine-tuning.
Hope I've helped. :)

Related

Invariant Violation: Element type is invalid expected a string (for built-in components)...but got: undefined

The error message is:
Invariant Violation: Element type is invalid expected a string (for built-in components) or a class/function (for composite components) but got: undefined
I am new to react and can't find what is wrong with the code. The error message is telling me to "Check the render method of 'LoginScreen'".
My code:
// Import React Navigation
import {
createBottomTabNavigator,
createStackNavigator,
} from 'react-navigation';
import tabBarIcon from './utils/tabBarIcon';
// Import the screens
import FeedScreen from './screens/FeedScreen';
import NewPostScreen from './screens/NewPostScreen';
import SelectPhotoScreen from './screens/SelectPhotoScreen';
import React, {Component, Button} from 'react';
/*export default class App extends Component<Props> {
render(){
<View>
</View>
}
}*/
class LoginScreen extends Component {
login() {
this.props.navigation.navigate('Main');
}
render() {
return <Button title='Login' onPress={() => {this.login()}} />;
}
}
// Create our main tab navigator for moving between the Feed and Photo screens
const navigator = createBottomTabNavigator(
{
// The name `Feed` is used later for accessing screens
Feed: {
// Define the component we will use for the Feed screen.
screen: FeedScreen,
navigationOptions: {
// Add a cool Material Icon for this screen
tabBarIcon: tabBarIcon('home'),
},
},
// All the same stuff but for the Photo screen
Photo: {
screen: SelectPhotoScreen,
navigationOptions: {
tabBarIcon: tabBarIcon('add-circle'),
},
},
},
{
// We want to hide the labels and set a nice 2-tone tint system for our tabs
tabBarOptions: {
showLabel: false,
activeTintColor: 'black',
inactiveTintColor: 'gray',
},
},
);
// Create the navigator that pushes high-level screens like the `NewPost` screen.
const stackNavigator = createStackNavigator(
{
Main: {
screen: navigator,
// Set the title for our app when the tab bar screen is present
navigationOptions: { title: 'Insta' },
},
// This screen will not have a tab bar
NewPost: NewPostScreen,
},
{
cardStyle: { backgroundColor: 'white' },
},
);
const TopLevelNav = createStackNavigator({
Login: { screen: LoginScreen },
Main: { screen: stackNavigator },
}, {
headerMode: 'none',
});
// Export it as the root component
export default TopLevelNav;
Button isn't exported from react. Its part of react-native. Source.
Change to:
import React, { Component } from 'react';
import { Button } from 'react-native';
This error is typically seen when you have an incorrect import. Common reasons include:
Forgetting to export/import entirely
Using a mismatched type of import (default/named)
Importing from the wrong library or path
In this case it was just being imported from the wrong package which will make it undefined.

React Native Navigation from Child Components

I'm trying to implement a simple navigation between screens, but getting this error:
Undefined is not an object 'this.props.navigate'
AppNavigator.js
let AppNavigator = createStackNavigator({
Signup:
{ screen: SignupScreen,
navigationOptions: {
header: null
}
},
Login: { screen: LoginScreen,
navigationOptions: {
header: null
}
},
},{
initialRouteName: "Signup"
});
SignupScreen.js
<View>
<SignupForm/>
</View>
SignupForm.js
const { navigate } = this.props.navigation;
<Text onPress={() =>
navigate('Login')
}>
¿Allready have an account? Sign in
</Text>
I guess the problem is that there si something additional to do in child components cases. Please help.
You should pass navigation to SignupForm. Choose 1 of 2 solution below
1.
<View>
<SignupForm navigation={this.props.navigation} />
</View>
or
in SignupForm.js
import { withNavigation } from 'react-navigation';
export default withNavigation(SignupForm);
You must use withNavigation if you use separate component see the documentation about withNavigation : here
You might have missed wrapping your AppNavigator in a NavigationContainer before using it elsewhere.
in your AppNavigator.js
import { createAppContainer } from 'react-navigation'; // add this
import { createStackNavigator } from 'react-navigation-stack'; // i trust you've already got this
let AppNavigator = createStackNavigator({
Signup:
{ screen: SignupScreen,
navigationOptions: {
header: null
}
},
Login: { screen: LoginScreen,
navigationOptions: {
header: null
}
},
},{
initialRouteName: "Signup"
});
export default createAppContainer(AppNavigator); // this is important!
I actually don't think there's anything special you need to do for child components to work. That AppContainer is for ensuring correct props are passed to child components. Refer to documentation for a bit more context.

Problem to return component from StackNavigator in react-native. Get a blank screen but cosole.log is OK

What I want to do is wrapp on the very top of my app a switch navigator named MainNavigator which redirect to a LoadingScreen who determine if user is Logged or no and navigate to AuthNavigator or AppNavigator.
AuthNavigator himself is a stackNavigator who display screens 'LoginScreen' or 'SignUpScreen'.
AppNavigator is a DrawerNavigator with multiple screens (Profile, Home...).
The problem I encouter is that the return method seems to work, because I can see the logs in my console from the 'LoginScreen' component but on the screen, the only return is a white screen.. When I call directly my 'LoginScreen' component from the LoadingScreen component by using :
_bootstrapAsync = async () => {
const userToken = await AsyncStorage.getItem('userToken');
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away. switched to develop the app
this.props.navigation.navigate(userToken ? 'App' : 'LoginScreen');
};
I had the LoginScreen component rendered on my device.
I know the problem come from my AuthNavigator and AppNavigator because I can return screens components from AuthLoading or MainNavigator
Here some code :
* Main Navigator: entry point of the app
* Redirect to AuthLoadingScreen by default,
* if user is signed (AsyncStorage) or successly signIn
* redirect to AppNavigator else if user isn't SignIn
* go to AuthNavigator
import { createAppContainer, createSwitchNavigator } from 'react-
navigation';
import AuthNavigator from './auth/AuthNavigator'
import AppNavigator from './app/AppNavigator'
import AuthLoadingScreen from '../screens/auth/AuthLoadingScreen'
export default createAppContainer(createSwitchNavigator(
{
// You could add another route here for authentication.
// Read more at https://reactnavigation.org/docs/en/auth-flow.html
AuthLoading: AuthLoadingScreen,
App: AppNavigator,
Auth: AuthNavigator,
},
{
initialRouteName: 'AuthLoading',
}
));
AuthLoading :
import React from 'react';
import {
ActivityIndicator,
AsyncStorage,
StatusBar,
StyleSheet,
View,
Text
} from 'react-native';
export default class AuthLoadingScreen extends React.Component {
constructor(props) {
super(props);
this._bootstrapAsync();
}
// Fetch the token from storage then navigate to our appropriate place
_bootstrapAsync = async () => {
const userToken = await AsyncStorage.getItem('userToken');
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away. switched to develop the app
this.props.navigation.navigate(userToken ? 'App' : 'Auth');
};
// Render any loading content that you like here
render() {
return (
<View>
<Text>Loading</Text>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
AuthNavigator:
import { createStackNavigator } from 'react-navigation';
import LoginScreen from '../../screens/auth/LoginScreen';
import SignUpScreen from '../../screens/auth/SignUpScreen';
export default createStackNavigator({
Login : {
screen : LoginScreen
},
SignUp: {
screen : SignUpScreen
}
},
{
initialRouteName: 'Login',
})
LoginScreen:
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default class LoginScreen extends Component {
render() {
console.log('LOGIN SCREEN')
return (
<View style={styles.container}>
<Text style={styles.text}>Login</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text : {
fontSize: 20,
}
});
I can't find the error, but I know it comes from the AuthNavigator and AppNavigator. I can see the 'LOGIN SCREEN' or 'APP SCREEN' if I set the AuthLoading route to render App in my console but nothing on the screen, when I init a new route LoginScreen in my MainNavigator and navigate to that route from the AuthLoading it works, I have a beautiful text displayed on my screen.
I Know it's probably an insignifiant error but I spend hours to fix this by myself and can't find, so if someone can help me it would be nice!
Thanks by advance!
Problem solved... Because at the top of my app in App.js I wrapped my MainNavigator like that
<View>
<StatusBar hidden={true} />
<MainNavigator />
</View>
So I remove the view and statusbar... and it works. 4 days to figure it out... I love it! :')

Cannot Deep Link Into Nested React Native Navigators

I'm experiencing an issue with React Navigation 2.18.3. I cannot deep link to a route that belongs to a navigator that is nested. I have a top-level tab navigator, MainTabNavigator which has two routes, Home and Menu:
import React, { PureComponent } from 'react';
import { createMaterialTopTabNavigator } from 'react-navigation';
import Explore from '../Home/Home';
import Menu from '../Menu/Menu';
import { TabBarContainer as TabBar } from './TabBar';
class MainTabNavigator extends PureComponent {
getRoutes() {
return {
Explore: { screen: Explore },
Menu: { screen: Menu, path: 'menu' }
};
}
getOptions() {
return {
tabBarComponent: TabBar,
tabBarPosition: 'bottom',
swipeEnabled: false
};
}
render() {
const TabNavigator = createMaterialTopTabNavigator(
this.getRoutes(),
this.getOptions()
);
return (
<TabNavigator uriPrefix="myapp://" />
);
}
}
export default MainTabNavigator;
Menu itself is a stack navigator:
import React, { Component } from 'react';
import { createStackNavigator } from 'react-navigation';
import MenuPage from './MenuPage';
import Products from '../Products/Products';
import onNavigationStateChange from '../../util/onNavigationStateChange';
import Settings from './Settings/Settings';
class Menu extends Component {
getRoutes() {
return {
MenuPage: { screen: MenuPage, path: 'page' },
Products: { screen: Products, path: 'products' },
Settings: { screen: Settings }
};
}
getOptions() {
return {
initialRouteName: 'MenuPage',
headerMode: 'none',
cardStyle: { backgroundColor: '#fff' }
};
}
render() {
const Navigation = createStackNavigator(this.getRoutes(), this.getOptions());
const screenProps = { rootNavigation: this.props.navigation };
return (
<Navigation
uriPrefix="myapp://menu"
screenProps={screenProps}
onNavigationStateChange={onNavigationStateChange}
/>
);
}
}
export default Menu;
When I go to safari and navigate to myapp://menu/products, the Menu navigator navigates correctly, but the MainTabNavigator stays stuck on Home. To the user, it looks like no navigation took place. If the user then navigates to the Menu, they will find that the Menu is already navigated to the Products page.
How can I get MainTabNavigator to navigate correctly when responding to a deep link?
To anyone experiencing a similar problem:
The issue was that we were explicitly rendering our Navigators. As it says in the "Common Mistakes" section of the docs:
Most apps should only ever render one navigator inside of a React component, and this is usually somewhere near the root component of your app. This is a little bit counter-intuitive at first but it's important for the architecture of React Navigation.
Apparently, failing to do so prevents you from being able to deep link all the way through your navigators ¯\_(ツ)_/¯

How to get current navigation state

I am using React Navigation's Tab Navigator from https://reactnavigation.org/docs/navigators/tab, when I switch between the Tab Screens I don't get any navigation state in this.props.navigation.
Tab Navigator:
import React, { Component } from 'react';
import { View, Text, Image} from 'react-native';
import DashboardTabScreen from 'FinanceBakerZ/src/components/dashboard/DashboardTabScreen';
import { TabNavigator } from 'react-navigation';
render() {
console.log(this.props.navigation);
return (
<View>
<DashboardTabNavigator />
</View>
);
}
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
},
THISWEEK: {
screen: DashboardTabScreen
}
});
DASHBOARD SCREEN:
import React, { Component } from 'react';
import { View, Text} from 'react-native';
export default class DashboardTabScreen extends Component {
constructor(props) {
super(props);
this.state = {};
console.log('props', props);
}
render() {
console.log('props', this.props);
return (
<View style={{flex: 1}}>
<Text>Checking!</Text>
</View>
);
}
}
I get props at Dashboard Screen when it renders the component first but I don't get props when I switch the tabs.
I need to get the current Screen name i.e TODAY or THISWEEK.
Your problem is about "Screen Tracking", react-navigation has an officially guide for this. you can use onNavigationStateChange to track the screen by using built-in navigation container or write a Redux middleware to track the screen if you want to integrate with Redux. More detail can be found at the officially guide: Screen-Tracking. Below is a sample code from the guide by using onNavigationStateChange:
import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';
const tracker = new GoogleAnalyticsTracker(GA_TRACKING_ID);
// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getCurrentRouteName(route);
}
return route.routeName;
}
const AppNavigator = StackNavigator(AppRouteConfigs);
export default () => (
<AppNavigator
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = getCurrentRouteName(currentState);
const prevScreen = getCurrentRouteName(prevState);
if (prevScreen !== currentScreen) {
// the line below uses the Google Analytics tracker
// change the tracker here to use other Mobile analytics SDK.
tracker.trackScreenView(currentScreen);
}
}}
/>
);
Check all properties first, like
<Text>{JSON.stringify(this.props, null, 2)}</Text>
Above json array will show you current state of navigation under routeName index i.e.
this.props.navigation.state.routeName
Have you tried to define navigationOptions in your route object?
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
navigationOptions: {
title: 'TODAY',
},
},
})
You can also set navigationOptions to a callback that will be invoked with the navigation object.
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
navigationOptions: ({ navigation }) => ({
title: 'TODAY',
navigationState: navigation.state,
})
},
})
Read more about navigationOptions https://reactnavigation.org/docs/navigators/
Answer as of React Navigation v6
Depending on whether you want to trigger re-renders on value changes:
const state = navigation.getState();
or
const state = useNavigationState(state => state);
Reference:
https://reactnavigation.org/docs/use-navigation-state#how-is-usenavigationstate-different-from-navigationgetstate

Resources