I have a stack navigator set up in the following way
const wishlizt = StackNavigator({
Splash: {screen: SplashScreen},
SignIn: {screen: SignInScreen},
SignUp: {screen: SignUpScreen},
Profile: {screen: ProfileScreen},
Home: {screen: MainScreenNavigator},
Chat: {screen: ChatScreen}
},
{
navigationOptions: {
title: 'Wishlizt',
header: {
style: {
backgroundColor: Colors.bgBrand,
elevation: null,
},
titleStyle: {
color: Colors.lightest
},
right: <HeaderRight />
}
},
initialRouteName: 'Splash'
});
As you can see I use a component HeaderRight in my header which contains some icons - settings cog, profile, etc. I want to be able to navigate from those icons' TouchableOpacity onPress method. But the navigation prop 'this.props.navigation' is missing in that component.
The official documentation page has this code sample on how to call navigate on the top level component and recommends using 'ref'
const AppNavigator = StackNavigator(SomeAppRouteConfigs);
class App extends React.Component {
someEvent() {
// call navigate for AppNavigator here:
this.navigator && this.navigator.dispatch({ type: 'Navigate', routeName, params });
}
render() {
return (
<AppNavigator ref={nav => { this.navigator = nav; }} />
);
}
}
I am unable to see how this can work in my example. Can anyone help on this? Thanks
Huge
The header property can be a function as well as an object. When it is a function, the navigation object is passed in as the first parameter, it can then be passed to the HeaderRight component as a prop.
navigationOptions: {
header: (navigation) => {
return {
style: {
backgroundColor: Colors.bgBrand,
elevation: null,
},
titleStyle: {
color: Colors.lightest
},
right: (<HeaderRight
navigation={navigation}
/>),
};
},
},
I don't know if this helps, I am researching why my call isn't working either in react-navigation. But your braces are messed up in your example. You have initial route name inside of the navigation options, which might be right, but your indenting shows a whole other story...
If you want to "call navigate on the top level" or if you don't have the navigation prop available you can do so as described here: https://reactnavigation.org/docs/navigating-without-navigation-prop/
Use ref in the NavigationContainer:
// App.js
import { NavigationContainer } from '#react-navigation/native';
import { navigationRef } from './RootNavigation';
export default function App() {
return (
<NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
);
}
Create RootNavigation.js where you define your dispatches:
// RootNavigation.js
import { createNavigationContainerRef } from '#react-navigation/native';
export const navigationRef = createNavigationContainerRef()
export function navigate(name, params) {
if (navigationRef.isReady()) {
navigationRef.navigate(name, params);
}
}
// add other navigation functions that you need and export them
You can then use your RootNavigation to navigate to the desired screen from anywhere:
// any js module
import * as RootNavigation from './path/to/RootNavigation.js';
// ...
RootNavigation.navigate('ChatScreen', { userName: 'Lucy' });
Related
I have created a navigation setup for my application that should start off with a welcome screen on the welcome screen you find two buttons, one for registering and the other for logging in.
When the user registers or logs in he get sent to other screens. I have created a stack navigator between the log in and register screen and put them in a loginFlow constant and another between the welcome screen and the loginFlow constant and the navigation between these screens works, but for some reason the welcome screen doesn't get shown first instead I get the sign up screen (register screen).
Why is that the case and how can i make the welcomeScreen get shown first
import React from "react";
import { View } from "react-native";
import WeclomeScreen from "./app/screens/WelcomeScreen";
import MainScreen from "./app/screens/MainScreen";
import AccountScreen from "./app/screens/AccountScreen";
import { Provider as AuthProvider } from "./app/context/AuthContext";
import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs";
import SignupScreen from "./app/screens/SignupScreen";
import { createAppContainer, createSwitchNavigator } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import ResultShowScreen from "./app/screens/ResultShowScreen";
import ResolveAuthScreen from "./app/screens/ResolveAuthScreen";
import SigninScreen from "./app/screens/SigninScreen";
import ArticleSaveScreen from "./app/screens/ArticleSaveScreen";
import { setNavigator } from "./app/navigationRef";
const articleListFlow = createStackNavigator({
Main: MainScreen, // screen with diffrent articles categories
ResultsShow: ResultShowScreen, // article details screen
});
const loginFlow = createStackNavigator({
Signup: SignupScreen,
Signin: SigninScreen,
});
loginFlow.navigationOptions = () => {
return {
headerShown: false,
};
};
articleListFlow.navigationOptions = {
title: "News Feed",
tabBarIcon: ({ tintColor }) => (
<View>
<Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} />
</View>
),
activeColor: "#ffffff",
inactiveColor: "#ebaabd",
barStyle: { backgroundColor: "#d13560" },
};
const switchNavigator = createSwitchNavigator({
ResolveAuth: ResolveAuthScreen,
MainloginFlow: createStackNavigator({
WelcomeScreen: WeclomeScreen,
loginFlow: loginFlow,
}),
mainFlow: createMaterialBottomTabNavigator(
{
articleListFlow: articleListFlow,
ArticleSave: ArticleSaveScreen, // we dont need this one
Account: AccountScreen,
},
{
activeColor: "#ffffff",
inactiveColor: "#bda1f7",
barStyle: { backgroundColor: "#6948f4" },
}
),
});
const App = createAppContainer(switchNavigator);
export default () => {
return (
<AuthProvider>
<App
ref={(navigator) => {
setNavigator(navigator);
}}
/>
</AuthProvider>
);
};
here is the content of ResolveAuthscreen :
import React, { useEffect, useContext } from "react";
import { Context as AuthContext } from "../context/AuthContext";
const ResolveAuthScreen = () => {
const { tryLocalSignin } = useContext(AuthContext);
useEffect(() => {
tryLocalSignin();
}, []);
// not returning anything since just waiting to check the token
// will transition to signin or signup very quickly
return null;
};
export default ResolveAuthScreen;
As you have mentioned in your comments, you have an issue in your tryLocalSignin method. In that method, if there is no any token, you are navigating the user to the Signup screen. Instead of navigating to the Signup screen, navigate to the WelcomeScreen screen like:
const tryLocalSignin = (dispatch) => async () => {
const token = await AsyncStorage.getItem("token");
if (token) {
dispatch({ type: "signin", payload: token });
navigate("Main");
} else {
navigate("WelcomeScreen");
}
};
I'm sorry for the what might turn out to be a very stupid question, but for some time now I'm struggling with the following issue, but I'm new to react-native.
I create a react-native app in which I implement the react-navigation-drawer navigation precisely as in the example.
What happens is that whenever I open the App the drawer is opened. The same things happens when i copy and paste the example from here: https://reactnavigation.org/docs/en/drawer-based-navigation.html
This makes me think I'm missing something with the dependencies. I've upgraded all i could think of from the needed librabries. My CPU is not a good one so I'm using my Android phone for testing.
I also get the warning "componentWillMount has been renamed..." when i use the react-navigation-drawer.
If you could help guide me to some information that would be helpful!
Thank you all in advance!
Below is some code for an example:
import React from 'react';
import { FlatList, ActivityIndicator, Text, Header, Image, View, ScrollView, Alert, TouchableWithoutFeedback, TouchableOpacity, TouchableHighlight, StyleSheet } from 'react-native';
import {Button, Icon, ThemeProvider} from 'react-native-elements';
import {createAppContainer, DrawerNavigator, withNavigation} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import {createDrawerNavigator, DrawerActions, DrawerLayoutAndroid} from 'react-navigation-drawer';
.....
const Screen1PageScreenStack = createStackNavigator({
Screen1Page: {
screen: Screen1Page,
}
},{
navigationOptions: ({ navigation }) => ({
initialRouteName: 'Screen1Page',
headerMode: 'screen',
drawerLabel: 'HOME',
drawerBackgroundColor: '#0000FF',
}
)
});
const Screen2PageScreenStack = createStackNavigator({
Screen2Page: {
screen: Screen2Page,
}
},{
navigationOptions: ({ navigation }) => ({
initialRouteName: 'Screen2Page',
headerMode: 'screen',
drawerLabel: 'Categories',
}
),
});
const appNavigator = createDrawerNavigator({
Screen1Page: {
name: 'Screen1PageScreenStack',
screen: Screen1PageScreenStack,
},
Screen2Page: {
name: 'Screen2PageScreenStack',
screen: Screen2PageScreenStack,
}
});
const MyDrawerStrugglesApp = createAppContainer(appNavigator);
export default MyDrawerStrugglesApp ;
You can try this code to keep your drawer hidden for required screen :
const Nav = createDrawerNavigator(
{
Home: {
screen: AppLogin,
navigationOptions:{
drawerLockMode: 'locked-closed',
drawerLabel: <Hidden />
},
},
}
);
Your Hidden class should be as follows :
class Hidden extends React.Component {
render() {
return null;
}
}
You can change the drawerLockMode value to keep the drawer opened or closed - Refer here for different values.
Also you can refer this SO answer here for avoiding the componentWillMount deprecation error. Hope this helps !
With react-navigation V5 you can pass the openByDefualt prop
<Drawer.Navigator
initialRouteName="Home"
openByDefault>
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="Notifications" component={NotificationsScreen} />
</Drawer.Navigator>
With react-navigation v6 all you need to do is pass defaultStatus="closed" prop directly to Drawer.Navigator. The app will always load with the drawer closed.
I wish to utilize an in-app notification system, aka a more attractive and less in your face' use of alerts to let the user know what actions are being done, especially when for instance a barcode has been detected but it needs to send that barcode to the server and the user needs to wait.
I have found this lib and have attempted to implement it; but as I am using React Navigation and I wish to render the item at the very top of the application, it gets cut off by React Native header
Is it possible to have a function I can create and reference whenever I want a global notification and it will render on the very top I would imagine it would need to render here:
import React from 'react';
import { createBottomTabNavigator,createStackNavigator } from 'react-navigation';
import SearchTab from './components/Tabs/SearchTab';
import HomeTab from './components/Tabs/HomeTab';
import ScannerTab from './components/Tabs/ScannerTab';
import SettingsTab from './components/Tabs/SettingsTab';
import Ionicons from 'react-native-vector-icons/Ionicons';
import StockModal from './components/Modals/StockModal';
const MainStack = createBottomTabNavigator(
{
Home: HomeTab,
Search: SearchTab,
Scanner: ScannerTab,
Settings: SettingsTab,
//Todo: Total overlay modals HERE
},
{
navigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, tintColor }) => {
const { routeName } = navigation.state;
let iconName;
if (routeName === 'Home') {
iconName = `ios-information-circle${focused ? '' : '-outline'}`;
} else if (routeName === 'Settings') {
iconName = `ios-options${focused ? '' : '-outline'}`;
}else if (routeName === 'Scanner') {
iconName = `ios-barcode${focused ? '' : '-outline'}`;
}else if (routeName === 'Search') {
iconName = `ios-search${focused ? '' : '-outline'}`;
}
return <Ionicons name={iconName} size={25} color={tintColor} />;
},
}),
tabBarOptions: {
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
},
}
);
export default RootStack = createStackNavigator(
{
Main: {
screen: MainStack,
},
QuickStockScreen: {
screen: StockModal,
},
},
{
mode: 'modal',
headerMode: 'none',
}
);
But even if that's possible, I am not sure how its possible to build a function that tells the notification to show; React Redux comes to mind but I don't wish to implement such a cumbersome system just for one feature and it was something I considered when creating his application and decided against.
The notification system in question (not very clear documentation or examples sadly) https://www.npmjs.com/package/react-native-in-app-notification
Here is the navigation lib I am using: https://reactnavigation.org/
What you want would be a component that is a the same level of the navigation (So it can display over it). In multiple projects, I use react-native-root-siblings to do so. It allows you to add UI over the app and so over the navigation.
An exemple how what I made with it. The dark layer and the box at the bottom are part of the Siblings Component.
https://gyazo.com/7ad3fc3fea767ea84243aaa493294670
The Siblings is used like the Alert of React-Native, so as a function (which is quite useful!)
messageMenu.js
import React, { Component } from 'react';
import RootSiblings from 'react-native-root-siblings';
import MessageMenuContainer from './MessageMenuContainer';
export default class Dialog extends Component {
static show = (props) => new RootSiblings(<MessageMenuContainer {...props} />);
static update = (menu, props) => {
if (menu instanceof RootSiblings) {
menu.update(<MessageMenuContainer {...props} />);
} else {
console.warn(`Dialog.update expected a \`RootSiblings\` instance as argument.\nBut got \`${typeof menu}\` instead.`);
}
}
static close = (menu) => {
if (menu instanceof RootSiblings) {
menu.destroy();
} else {
console.warn(`Dialog.destroy expected a \`RootSiblings\` instance as argument.\nBut got \`${typeof menu}\` instead.`);
}
}
render() {
return null;
}
}
export {
RootSiblings as Manager,
};
Where the MessageMenuContainer is your component to render at the top.
Component using the Root Siblings:
import React from 'react';
import PropTypes from 'prop-types';
import I18n from 'react-native-i18n';
import { BackHandler, Keyboard, Platform, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import DraftMenu from './messageMenu'; //HERE IS THE IMPORT YOU WANT
import { Metrics, Colors, Fonts } from '../../main/themes';
class DraftBackButton extends React.Component {
state = {
draftMenu: undefined,
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackAndroid);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackAndroid);
}
handleBackAndroid = () => {
this.handleBack();
return true;
}
handleBack = async () => {
Keyboard.dismiss();
await this.openDraftMenu();
}
openDraftMenu = async () => {
if (this.state.draftMenu) {
await DraftMenu.update(this.state.draftMenu, this.draftMenuProps());
} else {
const draftMenu = await DraftMenu.show(this.draftMenuProps());
this.setState({ draftMenu: draftMenu });
}
}
draftMenuProps = () => ({
options: [
{ title: I18n.t('message.deleteDraft'), onPress: this.deleteDraft, icon: 'trash' },
{ title: I18n.t('message.saveDraft'), onPress: this.saveOrUpdateDraft, icon: 'documents' },
{ title: I18n.t('cancel'), icon: 'close', style: { backgroundColor: Colors.tertiaryBackground } },
],
destroyMenuComponent: async () => {
DraftMenu.close(this.state.draftMenu);
await this.setState({ draftMenu: undefined });
},
withIcon: true,
})
saveOrUpdateDraft = async () => {
// SAVE OR UPDATE DRAFT. NOT IMPORTANT
}
saveDraft = async () => {
// SAVING THE DRAFT
}
updateDraft = async () => {
// UPDATING THE DRAFT
}
deleteDraft = async () => {
// DELETING THE DRAFT
}
render() {
return (
<TouchableOpacity
hitSlop={Metrics.touchable.largeHitSlop}
onPress={() => {
this.handleBack();
}}
>
<Text>BUTTON</Text>
</TouchableOpacity>
);
}
}
DraftBackButton.propTypes = {
// ALL THE PROPTYPES
};
function mapStateToProps(state, ownProps) {
//
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({ fetchMessages }, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(DraftBackButton);
The best thing with this lib is that you can call the .show anywhere in your app and it will render at the very top!
Hope it's what you're looking for!
EDIT:
I updated the example of how to use the Root Siblings.
Here's the content of my MessageContainer which will be display on top of everything
import React from 'react';
import PropTypes from 'prop-types';
import { Animated, Dimensions, InteractionManager, StyleSheet, TouchableOpacity, View } from 'react-native';
import MessageMenuItem from './MessageMenuItem';
import { Colors } from '../../../main/themes';
const { width, height } = Dimensions.get('window');
const OPTION_HEIGHT = 55;
const OVERLAY_OPACITY = 0.5;
export default class DraftMenuContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
animatedHeight: new Animated.Value(0),
animatedOpacity: new Animated.Value(0),
menuHeight: props.options.length * OPTION_HEIGHT,
};
}
componentDidMount() {
this.onOpen();
}
// Using Animated from react-native to make the animation (fade in/out of the dark layer and the dimensions of the actual content)
onOpen = async () => {
await this.state.animatedHeight.setValue(0);
await this.state.animatedOpacity.setValue(0);
Animated.parallel([
Animated.timing(this.state.animatedHeight, { toValue: this.state.menuHeight, duration: 200 }),
Animated.timing(this.state.animatedOpacity, { toValue: OVERLAY_OPACITY, duration: 200 }),
]).start();
}
onClose = async () => {
await this.state.animatedHeight.setValue(this.state.menuHeight);
await this.state.animatedOpacity.setValue(OVERLAY_OPACITY);
Animated.parallel([
Animated.timing(this.state.animatedHeight, { toValue: 0, duration: 200 }),
Animated.timing(this.state.animatedOpacity, { toValue: 0, duration: 200 }),
]).start(() => this.props.destroyMenuComponent()); // HERE IS IMPORTANT. Once you're done with the component, you need to destroy it. To do so, you need to set a props 'destroyMenuComponent' which is set at the creation of the initial view. See the other code what it actually do
}
render() {
return (
<View style={styles.menu}>
<Animated.View style={[styles.backgroundOverlay, { opacity: this.state.animatedOpacity }]}>
<TouchableOpacity
activeOpacity={1}
onPress={() => this.onClose()}
style={{ flex: 1 }}
/>
</Animated.View>
<Animated.View style={[styles.container, { height: this.state.animatedHeight }]}>
{this.props.options.map((option, index) => (
<MessageMenuItem
height={OPTION_HEIGHT}
icon={option.icon}
key={index}
onPress={async () => {
await this.onClose();
InteractionManager.runAfterInteractions(() => {
if (option.onPress) {
option.onPress();
}
});
}}
style={option.style}
title={option.title}
withIcon={this.props.withIcon}
/>
))}
</Animated.View>
</View>
);
}
}
DraftMenuContainer.propTypes = {
destroyMenuComponent: PropTypes.func.isRequired,
withIcon: PropTypes.bool,
options: PropTypes.arrayOf(PropTypes.shape({
icon: PropTypes.string.isRequired,
onPress: PropTypes.func,
title: PropTypes.string.isRequired,
})),
};
I trying to implement 2 type of Navigation in my apps, Tab Navigation and Stack Navigation.
My Desire Output:
But so far with my code, I only able to implement one of them.
const App = TabNavigator({
HomeScreen: { screen: HomeScreen },
ProfileScreen: { screen: ProfileScreen },
}, {
tabBarOptions: {
activeTintColor: '#7567B1',
labelStyle: {
fontSize: 16,
fontWeight: '600',
}
}
});
const Go = StackNavigator({
First: { screen: ProfileScreen },
Second: { screen: SecondActivity } },
});
export default rootNav;
What change should I make to my code to implement these 2 Navigation in my Apps?
Thank you.
You need a root StackNavigator, which has one route to your TabNavigator and one to your other StackNavigator. Then you can navigate from the TabNavigator to your other StackNavigator.
const rootNav = StackNavigator({
app: {screen: App},
go: {screen: Go},
});
const rootNav = StackNavigator({
app: {screen: App},
go: {screen: Go},
});
Method above can achieve the desire result however it may cause some issue, such as when perform Navigation to Screen, there will pop out 2 Header on Top of the Screen.
Improvement for Code above:
const rootNav = StackNavigator({
app: {screen: App},
First: { screen: ProfileScreen },
Second: { screen: SecondActivity },
});
My issue is I tried to implement 2 type of Nagivation Type in my Apps, TabNavigation and StackNavigation, so I using a root StackNavigator, which has one route to myTabNavigator and one to my other StackNavigator(Code Snippet of App.js). However, when I navigate to View Screen which is SecondActivity.js there will be two header pop out. I try to use header:null on SecondActivity.js but it will cause both header gone.
Is there any way to remove only 1 of the header from the SecondActivity.js Screen?
App.js (using RootNavigator to combine Tab and Stack Navigation in this Apps)
const App = TabNavigator({
HomeScreen: { screen: HomeScreen },
ProfileScreen: { screen: ProfileScreen },
}, {
tabBarOptions: {
activeTintColor: '#7567B1',
labelStyle: {
fontSize: 16,
fontWeight: '600'
}
}
});
const Go = StackNavigator({
First: { screen: ProfileScreen },
Second: { screen: SecondActivity }
});
const rootNav = StackNavigator({
app: {screen: App},
go: {screen: Go},
});
export default rootNav;
ProfileScreen.js
static navigationOptions = {
tabBarLabel: 'View/Edit',
header: null
}
// This Line Used to Navigate to SecondActivity.js Screen
OpenSecondActivity(id) {
this.props.navigation.navigate('Second', { ListViewClickItemHolder: id });
}
// The ListView onPress will call the function above.
<ListView
automaticallyAdjustContentInsets={false}
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.OpenSecondActivity.bind(this, rowData.RecipeID)}> {rowData.RecipeName} </Text>}
/>
SecondActivity.js
static navigationOptions = {
title: 'View Details',
};
Each StackNavigator has its own header.
this is happening you are using nested stackNavigator, so one header is because of Go (stackNavigator), and another one is because of rootNav (stackNavigator).
The Go StackNavigation is unnecessary instead change the rootNav into this:
const App = TabNavigator({
HomeScreen: { screen: HomeScreen },
ProfileScreen: { screen: ProfileScreen },
}, {
tabBarOptions: {
activeTintColor: '#7567B1',
labelStyle: {
fontSize: 16,
fontWeight: '600'
}
}
});
const rootNav = StackNavigator({
app: {screen: App},
First: { screen: ProfileScreen },
Second: { screen: SecondActivity }
});
export default rootNav;
This is happening because of the fact that the tab navigator is being rendered within the stack navigator.
Create a util file, and put this method on it. It resets the stack and put tab navigator on top
const resetActivities = (navigation, rootPath,props) => {
const stackAction = NavigationActions.reset({
index: 0,
key: null,
actions: [NavigationActions.navigate({ routeName: rootPath,params:props })],
});
navigation.dispatch(stackAction);
}
and pass the 'App', and the navigation object