I used createMaterialTopTabNavigator to create footer tab, like as below:
const TabNavigator = createMaterialTopTabNavigator(
{
HomeScreen: HomeScreen,
UserScreen: UserScreen,
},
{
initialRouteName: 'HomeScreen',
navigationOptions: {
header: null,
},
tabBarPosition: 'bottom',
tabBarComponent: FooterTabs,
},
);
and in FooterTabs on home screen button, i have this code:
if (this.props.navigation.state.index === 0) {
// i want call scrollToUp function in HomeScreen component
}
i want when user is in HomeScreen and press on home button react call scrollToUp method in HomeScreen.
===== resolved:
I added this code to HomeScreen:
componentDidMount() {
this.props.navigation.setParams({
onFocus: this.scrollToUp,
});
}
and edit FooterTabs like as below:
if (this.props.navigation.state.index === 0) {
this.props.navigation.state.routes[0].params.onFocus();
}
Hav you trid putting your Homescreen in a scrollView , and when the user presses home button ,
class HomeScreen extends Component {
render(){
return(
< ScrollView ref={(ref) => { this.scrollListReftop = ref; }}>
// your code here
< /ScrollView>
)
}
}
// add this to scroll to the top of scrollView inside your componentDidMount of Homescreen
componentDidMount(){
setTimeout(() =>this.scrollListReftop.scrollTo({x: 0, y: 0, animated: true}),10);
}
Hope its clear, feel free for any doubts.
Related
I am trying to hide bottomTabbar when I onPress a botton.
In my App.js file I have my ButtomTabNavigator :
const ButtomTabNavigator = createBottomTabNavigator(
{
screenOne: {
screen: RealReviewMain,
navigationOptions: ({ navigation }) => ({
tabBarVisible: true,
})
},
screenTwo: {
screen: RealReviewMain,
//Here I set the tabbarVisible to true
navigationOptions: ({ navigation }) => ({
tabBarVisible: true,
})
},
},
)
From ScreenTwo, I try to hide bottom tabbar using onPress
<TouchableOpacity
onPress={()=> {
this.props.navigation.setParams({ tabBarVisible: false });
}}/>
Is this the right way to do it? nothing happens.
Any advice or comment would be really appreciated! Thanks in advance!
It's possible to hide/show a tabBar based off button press. Using static navigationOptions. An example would be:
static navigationOptions = ({ navigation }) => {
return {tabBarVisible: navigation.state.params.tabBarVisible}
}
This is a simple example, you would need to initialize tabBarVisible since it would be false. A full component could look like:
import React, { Component } from 'react'
import { Text, View, Button } from 'react-native'
class Screen extends Component {
componentDidMount = () => {
this.props.navigation.setParams({ tabBarVisible: true }) //initialize the state
}
static navigationOptions = ({ navigation }) => {
return {tabBarVisible:navigation.state.params && navigation.state.params.tabBarVisible}
}
render() {
return (
<View style={{flex:1}}>
<Button title={"hide"} onPress={() => this.props.navigation.setParams({tabBarVisible:false})}/>
<Button title={"show"} onPress={() => this.props.navigation.setParams({tabBarVisible:true})}/>
</View>
)
}
}
export default Screen
As far as i know, you cannot hide navigation elements once they are rendered in the page.
But, as stated here you can hide navigation elements in specific screens as follows:
const FeedStack = createStackNavigator({
FeedHome: FeedScreen,
Details: DetailsScreen,
});
FeedStack.navigationOptions = ({ navigation }) => {
let tabBarVisible = true;
if (navigation.state.index > 0) {
tabBarVisible = false;
}
return {
tabBarVisible,
};
};
If you want to hide the navigator in a specific screen you can add an if condition:
if (navigation.state.index > 0 && navigation.state.routes[1].routeName === "<name of the screen>")
i'm new in react native. i want to add if condition in initialRouteName like code below. when "notification" variable is null move to "MemberProfile" page. but if "notification" variable is not null move to "ReviewMember" page. i try it code but still move to "MemberProfile" page. any solution?.
this is my code
var notification = null;
class DrawerMember extends Component {
constructor(props) {
super(props);
this.state = {
notifData: null
};
this.callCheck();
}
async callCheck() {
await AsyncStorage.getItem("#tryCode:notification", (err, result) => {
if (result != null) {
this.setState({
notifData: "testing data"
});
}
});
}
render() {
notification = this.state.notifData;
return <Root />;
}
}
const Root = createDrawerNavigator(
{
MemberProfile: {
screen: MemberProfileScreen
},
ReviewMember: {
screen: ReviewScreen
}
},
{
drawerPosition: "right",
initialRouteName: notification == null ? "MemberProfile" : "ReviewMember",
contentComponent: props => <SideBar {...props} />,
}
);
export default DrawerMember;
I think Root is created before the async function returns so notification is always null.
A possible way to solve this problem would be to use a SwitchNavigator as the first screen in your drawer. This navigator would be responsible for loading the notification and redirecting to the right screen.
Something along the lines of:
import React from 'react';
import { View, AsyncStorage, ActivityIndicator, StatusBar } from 'react-native';
export default class DummySwitch extends React.Component {
async componentDidMount() {
this.listener = this.props.navigation.addListener('willFocus', async () => {
const notification = await AsyncStorage.getItem('#tryCode:notification');
if (notification === null) {
this.props.navigation.navigate('MemberProfile');
}
else {
this.props.navigation.navigate('ReviewMember');
}
});
}
render() {
return (
<View>
<ActivityIndicator />
<StatusBar barStyle='default' />
</View>
);
}
}
As you can see, the switch screen just displays a loading button while accessing the async storage and deciding which route to take.
Then you define the drawer as usual but you add the switch screen as the initial route. You can also hide the label if you want by defining your own drawerLabel:
export default createDrawerNavigator({
Switch: {
screen: Switch,
navigationOptions: () => ({
drawerLabel: () => null,
}),
},
MemberProfile: {
screen: MemberProfileScreen,
},
ReviewMember: {
screen: ReviewScreen,
},
}, { initialRouteName: 'Switch' });
This is it, the drawer now selects the route based on your async storage.
I'm working with React Native and React Navigation.
I have a component called App.js in which I declare the Drawer Navigation of React-Navigation.
In this I have an option to log out but I can not navigate to another component after removing the AsyncStorage
Does anyone know how to achieve it?
Thank you.
This is my code:
App.js
import { createDrawerNavigator, DrawerItems, NavigationActions } from 'react-navigation';
const customDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems
{...props}
/>
<TouchableOpacity style={styles.button} onPress={this.logOut} >
<Text> Logout </Text>
</TouchableOpacity>
</ScrollView>
</SafeAreaView>
);
logOut = () => {
// NOT WORKS
// this.props.navigation.navigate('Login')
//NOT WORKS:
this.myAction();
}
myAction = () => {
const nav = NavigationActions.navigate({
routeName: 'App',
});
return nav;
};
const AppDrawNavigator = createDrawerNavigator(
{
MainComponent: { screen: MainComponent,
navigationOptions: ({navigation}) => ({
drawerLockMode: 'locked-closed'
}) },
Login: { screen: LoginComponent,
navigationOptions: ({navigation}) => ({
drawerLockMode: 'locked-closed'
}) },
User: { screen: UsersComponent }
},
{
contentComponent: customDrawerComponent,
}
);
make this as a class like
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
From your question I understand that either you want to :-
navigate from outside the components
navigate from components which do not have navigation prop.
For this I have tried 2 solutions and both work extremely fine though I based towards the second one.
First Solution
Use withNavigation from react-navigation package. If your components are deeply nested they wont have navigation prop unless u specify them manually or put them in context ;passing navigation prop becomes a real pain. So instead use withNavigation and your component would have navigation prop.
import {withNavigation} from "react-navigation";
const Component = ({navigation}) => {
const onPress = () => {
navigation.navigate(//ROUTE_NAME//)
}
return (
<TouchableOpacity onPress={onPress}>
<Text>Navigate</Text>
</TouchableOpacity>
)
}
export default withNavigation(Component);
Second Solution
Create a helper script and use that.
"use strict";
import React from "react";
import {NavigationActions} from "react-navigation";
let _container; // eslint-disable-line
export const navigation = {
mapProps: (SomeComponent) => {
return class extends React.Component {
static navigationOptions = SomeComponent.navigationOptions; // better use hoist-non-react-statics
render () {
const {navigation: {state: {params}}} = this.props;
return <SomeComponent {...params} {...this.props} />;
}
}
},
setContainer: (container) => {
_container = container;
},
reset: (routeName, params) => {
_container.dispatch(
NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
type: "Navigation/NAVIGATE",
routeName,
params
})
]
})
);
},
goBack: () => {
_container.dispatch(NavigationActions.back());
},
navigate: (routeName, params) => {
_container.dispatch(
NavigationActions.navigate({
type: "Navigation/NAVIGATE",
routeName,
params
})
);
},
navigateDeep: (actions) => {
_container.dispatch(
actions.reduceRight(
(prevAction, action) =>
NavigationActions.navigate({
type: "Navigation/NAVIGATE",
routeName: action.routeName,
params: action.params,
action: prevAction
}),
undefined
)
);
},
getCurrentRoute: () => {
if (!_container || !_container.state.nav) {
return null;
}
return _container.state.nav.routes[_container.state.nav.index] || null;
}
};
In your parent component when you mount the navigation call following:-
"use strict";
import React from "react";
import App from "./routes";
import {navigation} from "utils";
class Setup extends React.Component {
render () {
return (
<App
ref={navigatorRef => {
navigation.setContainer(navigatorRef);
}}
/>
);
}
}
export default App;
Now, in your components you can directly use helpers from this script itself and navigation would be accessibly globally now.
import {navigate} from "utils/navigation";
For more details you can this thread
Your logout function is declared outside of the Navigator. This means you don't have access to the navigation prop there. However, your customDrawerComponent is a screen of your Navigator and it should have access to it.
So you can try something like this (props here are the props passed to the customDrawerComponent):
onPress={()=> {props.navigation.navigate("Login")}}
Plus your App.js seems kind of strange since you're not exporting any component. Have you pasted the whole code of App.js or just parts of it?
I have a button in header to open & close navigation drawer menu.
When I call below method from componentDidMount() it worked and opened the menu:
this.props.navigation.toggleDrawer();
But when I click the button it didn't work and just fade the screen!
Here is the component code :
export class Home extends BaseScreen {
constructor(props) {
super(props);
}
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return ({
headerStyle: {
backgroundColor: '#FF9800'
}
, headerRight: <UserCoins />
, headerLeft: <Button onPress={params.handlePress} title='Menu' />
, title: 'title'
})
}
_handlePress() {
this.props.navigation.toggleDrawer();
}
state = {
coins: 0,
}
//
componentDidMount() {
this.props.navigation.setParams({
handlePress: this._handlePress.bind(this)
});
//here working
this.props.navigation.toggleDrawer();
}
render() {
return (<Text />);
}
}
export default Home
My navigator structure is :
1.SwitchNavigator
2.BottomTabNavigator
3.DrawerNavigator
4.StackNavigator (Home component inside it)
You can call 'navigation' that you are passing into your static NavigationOptions rather than trying to bind it in the params for navigation.
Try this on your onPress Event for your button
onPress={() => navigation.navigate('DrawerToggle')}
I am using react navigation in my app, and when i am using reset for clearing the stack and navigating to other screen , it is showing weird animation, like first all the screens that were in stack are poped and then it navigates to the new screen.
Here is the code
//code for resetting the stack
Login.js
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({routeName: 'Home'})
],
})
this.props.navigation.dispatch(resetAction)
Route.js
Home: {
screen: Tab,
navigationOptions: {
...headerStyle,
}
},
Intro: {
screen: IntroScreen,
navigationOptions: {
header: null
}
},
LogIn: {
screen: LogIn,
navigationOptions: {
...headerStyle,
title: 'LogIn',
}
},
So it first goes to into screen and then to home screen, how to fix this so it directly goes to Home screen
If you remove
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({routeName: 'Home'})
],
})
this.props.navigation.dispatch(resetAction)
from your Login.js then the stack navigator automatically goes to the first screen in the StackNavigator , which in this case will be your Home: {...} screen.
There is no need for you to reset the stack.
If you want to navigate to another screen by pressing a button for example then use
import React, { Component } from 'react';
import {
View,
Button,
} from 'react-native';
import { StackNavigator } from 'react-navigation';
export default class Initial extends Component {
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={() => navigate('Login')}
title="Go to Login"
color="#357DED"
/>
</View>
);
}
}