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.
Related
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.
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'd like to get user image into the tabBarIcon just like Instagram does it. I can't figure out the way to do it.
I tried getting the state but on the init of the app the state is empty.
I've tried like
const store = store.getState().user
but it's undefined on app init
I have MainTabNavigator.js
ProfileStack.navigationOptions = {
tabBarLabel: () => {
return null
},
tabBarIcon: ({focused}) => (
<Image source={{uri: ???}}/>
)
}
const TabNavigator = createBottomTabNavigator({
HomeStack,
SearchStack,
DashboardStack,
ProfileStack,
});
TabNavigator.path = '';
export default TabNavigator;
I can't get the props or state since this isn't a class
The solution was quite simple.... I don't know why I didn't think of it earlier.
The trick was to create a component that would get the state from redux and when the state changes after the init, the state would finally have the Object and there the image path
ProfileStack.navigationOptions = {
tabBarLabel: () => {
return null
},
tabBarIcon: ({focused}) => (
<BottomTabImage focused={focused} />
)
}
See i changed it to BottomTabImage which is just a component
And this is the component file
BottomTabImage.js
import {connect} from 'react-redux';
class BottomTabImage extends Component {
render() {
const uri = this.props.auth.image !== undefined ?`http://localhost/storage/creator_images/${this.props.auth.image)}`: '';
return <Image style={styles.profileImage} source={{uri}} />
}
}
const styles = StyleSheet.create({
profileImage: {
...
}
});
function mapStateToProps(state) {
return {
auth: state.user.auth
}
}
export default connect(mapStateToProps, {})(BottomTabImage)
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 am new in react-native world. I have two screen 1). Home 2). Notification
I am navigating from Home to Notification screen. When I am in Notification Screen that time when I press back button on that condition I want to refresh Home Screen. Please suggest.
Thanks in Advance!
Could you give us a little bit more details ? Are you using a navigator like react-navigation ?
If you want to trigger a method of the parent component from a child component, you should use props.
So, you can do something like this, if you are managing your view by yourself:
export default class Wrapper extends Component
{
state = {screen: 'Home'}
useNewScreen = screenToUse => this.setState({screen: screenToUse})
reloadHome = () => yourFunctionToRefreshThePage
render = () =>
{
if (this.state.screen === 'Home')
return (<Home goToNotif={() => this.useNewScreen('Notif')} />);
else if (this.state.screen === 'Notif')
return (<Notif onGoBack={() => this.reloadHome()} />);
}
}
class Home extends Component
{
render = () =>
{
return (
<TouchableOpacity onPress={() => this.props.goToNotif()}/>
);
}
}
class Notif extends Component
{
render = () =>
{
return (
<TouchableOpacity onPress={() => this.props.onGoBack()}/>
);
}
}
If you are using react-navigation, you can use the same idea:
You navigate to the new page with a special props
this.props.navigation.navigate('Notif', {
onGoBack: () => this.refresh()
});
And when you want to go back, you can call this method
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack(null);
I hope this is clear enough :)
Firstly always save navigated key screen to any TempStore.
Secondly set time interval to watch and compare both watching screen key and current screen key to able to call the inserted function from the screen you want to wacth and insert the screen mode to the function event..
OnScreen.js
import React, { Component } from 'react';
import { TempStore } from './helpers';
import {
Text,
View
} from "native-base";
class OnScreen extends Component {
constructor(props) {
super(props);
this.state = {
lastValue:'active'
}}
startWatching=()=>{
if (this.interval) { return; }
this.interval = setInterval(this.checkView, 100);
}
stopWatching=()=>{
this.interval = clearInterval(this.interval);
}
componentDidMount(){
this.startWatching();
}
componentWillUnmount(){
this.stopWatching();
}
checkView =()=> {
const proState = {};
proState.currentRoute=TempStore({type:'get',name:'_currentRoute'})
if(!proState.currentRoute){
proState.currentRoute={routeName:'Home',key:'Home'}
}
if(!this.props.statekey){return false}
var isVisible;
if(this.props.statekey === proState.currentRoute.key){
isVisible='active'
}else{
isVisible='inactive'
}
// notify the parent when the value changes
if (this.state.lastValue !== isVisible) {
this.setState({
lastValue: isVisible
})
this.props.onChange(isVisible);
}
}
render = () => {
return (
<View></View>
);
}
}
export default OnScreen;
react-navigation App.js
.......
const AppNav = AppNavigator(AppNavigators)
function getActiveRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getActiveRouteName(route);
}
return route;
}
export default () =>
<Root>
<AppNav onNavigationStateChange={(prevState, currentState) => {
TempStore({type:'set',name:'_currentRoute',value:getActiveRouteName(currentState)})}}/>
</Root>;
AnyScreenYouWishToWatch.js
import OnScreen from '../../../helper/OnScreen';
......
OnActiveToggle=(str)=> {
if(str==='active'){
alert('active');}
else{
alert('inactive');}
}
.....
<OnScreen statekey={this.props.navigation.state.key} onChange={this.OnActiveToggle}/>