drawerLockMode : 'locked-closed' not working directly with createStackNavigator - android

When I specify drawerLockMode direactly with createStackNavigator it is not working.
const drawerStack = createStackNavigator({
HomeScreen: { screen: HomeScreen },
}, {
headerMode: 'screen',
navigationOptions: {
drawerLockMode:'locked-closed'
}
})
But when I use drawerStack variable to define navigationOptions, it is working.
drawerStack.navigationOptions = ({ navigation }) => {
drawerLockMode = 'locked-closed';
return {
drawerLockMode,
};
};
Am I doing any mistake when I am directly using it inside createStackNavigator?
Update
As #bennygenel suggested, we need to user drawerLockMode in drawerNavigator instead of stackNavigator. Here is what i have done.
const drawerNavigator = createDrawerNavigator({
drawerStack: drawerStack
}, {
contentComponent: DrawerComponent,
navigationOpions:{
drawerLockMode:'locked-closed'
}
})
But it is not working in this way also. The only way it is working is by using the const variable created using createStackNavigator or createDrawerNavigator

Try the following code, it's working for me:
const UserHome_StackNavigator = StackNavigator({
userHm: {
screen: UserHome,
navigationOptions: ({ navigation }) => ({
title: 'User screen title',
headerStyle: {
backgroundColor: 'white',
},
headerTintColor: 'black'
}),
},
});
UserHome_StackNavigator.navigationOptions = ({ navigation }) => {
let drawerLockMode = 'locked-closed';
//logic here to change conditionaly, if needed
return {
drawerLockMode,
};
};

in case someone need this:
const drawerNavigator = createDrawerNavigator({
drawerStack: drawerStack
}, {
contentComponent: DrawerComponent,
navigationOpions: ({navigation}) => {
let routeName = navigation.state.routes[navigation.state.routes.length-1].routeName;
if(['Animation', 'Splash', 'Intro', 'Login', 'Signup'].indexOf(routeName)>=0){
return {
drawerLockMode: 'locked-closed'
}
}
return {}
}
})

Related

React native deep linking not moving through to 2nd deep link

When using react native deep linking, I am struggling to use a uri with a 2nd path. There are examples in the documentation https://reactnavigation.org/docs/4.x/deep-linking
The issue I am having is blahh://account --android will link to the correct screen however, blahh://account/keys --android will not. This is the same if I add any path to the screens in the AccountStack
I am using react navigation version 4.
const AccountStack = createStackNavigator(
{
Account: {
screen: Account,
path: '',
navigationOptions: {
...accountNavigationOptions,
...Account.navigationOptions,
},
},
AccountLoginAndSecurity: {
screen: AccountLoginAndSecurity,
path: '',
navigationOptions: () => ({
...defaultNavigationOptions,
headerTransitionPreset: 'uikit',
}),
},
CreateAccount: {
screen: CreateAccount,
path: '',
navigationOptions: () => ({
...defaultNavigationOptions,
headerTransitionPreset: 'uikit',
}),
},
KeysList: {
screen: KeysList,
path: 'keys',
navigationOptions: () => ({
...defaultNavigationOptions,
headerTransitionPreset: 'uikit',
}),
},
AccountSwitch: createAnimatedSwitchNavigator(
{
AccountLoading: {
screen: AccountLoading,
path: '',
params: {
theme: 'orange',
navigateScreen: 'CreateAccountOrLogin',
},
},
CreateAccountOrLogin: CreateAccountOrLogin,
Continue: AccountMenu,
},
{
initialRouteName: 'AccountLoading',
transition: createSwitchTransition(),
}
),
},
{
defaultNavigationOptions: accountNavigationOptions,
}
);
export const TabNavigator = createBottomTabNavigator(
{
Explore: {
screen: ExploreStack,
path: '',
},
Bookings: {
screen: YourBookingsStack,
path: '',
},
Account: {
screen: AccountStack,
path: 'account',
},
},
{
defaultNavigationOptions: ({ navigation }) => ({
// eslint-disable-next-line react/display-name
tabBarIcon: ({ focused }): React.ReactNode => {
const { routeName } = navigation.state;
let iconName;
if (routeName === 'Explore') {
focused
? (iconName = require('assets/icons/bottom_tab_icons/explore_tab_icon.png'))
: (iconName = require('assets/icons/bottom_tab_icons/explore_tab_icon_unselected.png'));
} else if (routeName === 'Bookings') {
focused
? (iconName = require('assets/icons/bottom_tab_icons/bookings_tab_icon.png'))
: (iconName = require('assets/icons/bottom_tab_icons/bookings_tab_icon_unselected.png'));
} else if (routeName === 'Account') {
focused
? (iconName = require('assets/icons/bottom_tab_icons/account_tab_icon.png'))
: (iconName = require('assets/icons/bottom_tab_icons/account_tab_icon_unselected.png'));
}
return <Image source={iconName} />;
},
tabBarOptions: {
showLabel: false,
style: {
elevation: 3,
borderTopColor: 'transparent',
backgroundColor: '#fff',
height: 50,
},
},
}),
navigationOptions: () => ({
headerBackTitle: null,
headerTitleStyle: { color: 'orange' },
}),
}
);
I just looked at the codebase and Account links through to the account screen before going to the keys screen.
Account: {
screen: Account,
path: '',
navigationOptions: {
...accountNavigationOptions,
...Account.navigationOptions,
},
},
so the fix was to add an empty path to this in the accountstack then it worked fine when going to npx uri-scheme open blahh://account/keys --android

React-navigation dynamic child screens

I'm in the process of creating a social media app and I've the following diagram of screen transition:
Main -> Profile -> Followers -> John's Profile -> John's Followers ->
Emily's Profile -> ....
How can I implement a flow like this? Currently my router implementation is buggy, I can not go nested, it returns the previous screen.
Here is the part of the router to express my problem:
const appStack = createStackNavigator(
{
[PROFILE_STACK]: { screen: profileStack },
[PROFILE_FOLLOWERS_STACK]: { screen: profileFollowersStack },
[PROFILE_FOLLOWINGS_STACK]: { screen: profileFollowingsStack }
},
{
initialRouteName: PROFILE_STACK,
headerMode: "none"
}
);
const profileStack = createStackNavigator(
{
[PROFILE]: {
screen: UserProfileScreen,
navigationOptions: () => ({
header: null
})
}
},
{
initialRouteName: PROFILE
}
);
const profileFollowersStack = createStackNavigator(
{
[PROFILE_FOLLOWERS]: {
screen: UserFollowersScreen,
navigationOptions: () => ({
header: null
})
}
},
{
initialRouteName: PROFILE_FOLLOWERS
}
);
const profileFollowingsStack = createStackNavigator(
{
[PROFILE_FOLLOWINGS]: {
screen: UserFollowingsScreen,
navigationOptions: () => ({
header: null
})
}
},
{
initialRouteName: PROFILE_FOLLOWINGS
}
);
export const goUserProfile = function(navigation, userId) {
const { navigate } = navigation;
navigate(PROFILE_STACK, {
userId: userId
});
};
export const goUserFollowers = function(navigation, userId) {
const { push } = navigation;
push(PROFILE_FOLLOWERS_STACK, {
userId: userId
});
};
export const goUserFollowings = function(navigation, userId) {
const { push } = navigation;
push(PROFILE_FOLLOWINGS_STACK, {
userId: userId
});
};
The problem was I was using navigate() method in my goUserProfile(), not push(). After using push(), my problem is solved.
Reference:
React Navigation V2: Difference between navigation.push and navigation.navigate

Create DrawerNavigator inside StackNavigator

I have a bottomTabNavigator which looks like this.
const tabNavigator = createBottomTabNavigator({
[SCREEN1]: {
screen: StackNavigator1
},
[SCREEN2]: {
screen: StackNavigator2
},
[SCREEN3]: {
screen: SplashScreen
},
},
Now, how I do I go about creating a DrawerNavigator on each of the screens ? Creating on a normal screen is fairly straightforward. How to create it within a stackNavigator ?
its pretty straight forward. You set the DrawerNavigator as the screen component.
For example:
const dn1 = createDrawerNavigator({
[Screen1]: {
screen: Screen01
}
});
const dn2= createDrawerNavigator({
[Screen1]: {
screen: Screen02
}
});
const dn3 = createDrawerNavigator({
[Screen1]: {
screen: Screen03
}
});
const tabNavigator = createBottomTabNavigator({
[SCREEN1]: {
screen: dn1
},
[SCREEN2]: {
screen: dn2
},
[SCREEN3]: {
screen: dn3
},
}
This way you would have a separate DrawerNavigator for each tab.

Global in-app notifications

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,
})),
};

React-Native alternative to AlertIOS.prompt for android?

I am following a tutorial for react-native, however they are doing it for IOS, there is one part where they use AlertIOS.prompt like this
AlertIOS.prompt(
'Add New Item',
null,
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
{
text: 'Add',
onPress: (text) => {
this.itemsRef.push({ title: text })
}
},
],
'plain-text'
);
I am trying to remake this for android but cannot get it working, I did find this https://www.npmjs.com/package/react-native-prompt
import Prompt from 'react-native-prompt';
<Prompt
title="Say something"
placeholder="Start typing"
defaultValue="Hello"
visible={ this.state.promptVisible }
onCancel={ () => this.setState({
promptVisible: false,
message: "You cancelled"
}) }
onSubmit={ (value) => this.setState({
promptVisible: false,
message: `You said "${value}"`
}) }/>
However I cannot get this to work either, It is supposed to display the prompt when I press a button but nothing happens..
Here is the full original code with AlertIOS
'use strict';
import React, {Component} from 'react';
import ReactNative from 'react-native';
const firebase = require('firebase');
const StatusBar = require('./components/StatusBar');
const ActionButton = require('./components/ActionButton');
const ListItem = require('./components/ListItem');
const styles = require('./styles.js')
const {
AppRegistry,
ListView,
StyleSheet,
Text,
View,
TouchableHighlight,
AlertIOS,
} = ReactNative;
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyA9y6Kv10CAl-QOnSkMehOyCUejwvKZ91E",
authDomain: "dontforget.firebaseapp.com",
databaseURL: "https://dontforget-bd066.firebaseio.com",
storageBucket: "dontforget-bd066.appspot.com",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
class dontforget extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
})
};
this.itemsRef = this.getRef().child('items');
}
getRef() {
return firebaseApp.database().ref();
}
listenForItems(itemsRef) {
itemsRef.on('value', (snap) => {
// get children as an array
var items = [];
snap.forEach((child) => {
items.push({
title: child.val().title,
_key: child.key
});
});
this.setState({
dataSource: this.state.dataSource.cloneWithRows(items)
});
});
}
componentDidMount() {
this.listenForItems(this.itemsRef);
}
render() {
return (
<View style={styles.container}>
<StatusBar title="Grocery List" />
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderItem.bind(this)}
enableEmptySections={true}
style={styles.listview}/>
<ActionButton onPress={this._addItem.bind(this)} title="Add" />
</View>
)
}
_addItem() {
AlertIOS.prompt(
'Add New Item',
null,
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
{
text: 'Add',
onPress: (text) => {
this.itemsRef.push({ title: text })
}
},
],
'plain-text'
);
}
_renderItem(item) {
const onPress = () => {
AlertIOS.alert(
'Complete',
null,
[
{text: 'Complete', onPress: (text) => this.itemsRef.child(item._key).remove()},
{text: 'Cancel', onPress: (text) => console.log('Cancelled')}
]
);
};
return (
<ListItem item={item} onPress={onPress} />
);
}
}
AppRegistry.registerComponent('dontforget', () => dontforget);
Could anyone tell me how I could make this work for android?
I think you can use the following libraries : https://github.com/mmazzarolo/react-native-dialog
Example code to get user input are as follows (not in docs)
<Dialog.Container visible={true}>
<Dialog.Title>Account delete</Dialog.Title>
<Dialog.Description>
Do you want to delete this account? You cannot undo this action.
</Dialog.Description>
<Dialog.Input label="Cancel" onChangeText={(text) => this.setState({username : text})} />
<Dialog.Button label="Delete" onPress={() => {
console.log(this.state.username);
this.setState({promptUser : false});
}} />
</Dialog.Container>
These looks like a good alternative since its natively implemented
https://github.com/shimohq/react-native-prompt-android
Actually, you can use a cross-platform prompt component that works fine both on Android and Ios. The link is given below.
https://www.npmjs.com/package/react-native-prompt-crossplatform and its
repository
link is
https://github.com/Ramiah-Viknesh/react-native-prompt-crossplatform
I developed a small utility to solve this issue. It might be useful.
https://github.com/eleviven/react-native-alertbox

Categories

Resources