react-navigation: Full screen background with nested navigators - react-native

First of all, for anyone looking for a solution to show a full-screen background image with nested navigators, the code below will give a great headstart. I couldn't find any better resources and it took me a while to get this together.
Now onto the problem. The issue is that there seems to be no better way to show a consistent full-screen image background when using nested navigators which would be the most common use case for many apps. Ideally, you configure the background image for the RootStack and that would be it.
The problem with the code below is that the MenuStack will not show the background image even if wrapped inside a MenuStackWrapper and when trying to render the image in the Menu component itself, the image resizes differently and thus seems like it's moving.
const MenuStack = createStackNavigator(
{
Menu,
Log,
},
{
headerMode: 'none'
}
);
const MainStack = createBottomTabNavigator(
{
Now,
Today,
Menu: MenuStack
},
{
initialRouteName: 'Now',
tabBarOptions: {
style: {
backgroundColor: 'transparent'
}
}
}
);
class MainStackWrapper extends Component {
static router = MainStack.router;
render() {
return (
<ImageBackground source={require('./res/images/bgr.png')} style={{ width: '100%', height: '100%' }} imageStyle={styles.backgroundImage}>
<MainStack navigation={this.props.navigation} />
</ImageBackground>
);
}
}
const AppStack = createStackNavigator(
{
Main: MainStackWrapper,
Modal: ModalScreen
},
{
mode: 'modal',
headerMode: 'none',
cardStyle: {
backgroundColor: 'transparent'
}
}
);
const AuthStack = createSwitchNavigator({
SignIn,
SignUp,
ForgotPass
});
const RootStack = createSwitchNavigator(
{
AuthLoading,
Auth: AuthStack,
App: AppStack
},
{
initialRouteName: 'AuthLoading'
}
);
type Props = {};
export default class App<Props> extends Component {
render() {
return (
<ImageBackground source={require('./res/images/bgr.png')} style={{ width: '100%', height: '100%' }} imageStyle={styles.backgroundImage}>
<StatusBar barStyle="light-content" backgroundColor="transparent" translucent={true} />
<RootStack />
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
backgroundImage: {
resizeMode: 'cover',
width: null,
height: null,
backgroundColor: 'transparent',
flex: 1,
flexDirection: 'column'
}
});

Related

Nested Stack Navigator and Drawer Navigator in React Native

I have a couple of issues with setup Stack Navigator and Drawer Navigator. First and foremost, the below picture is the flow that I expected and I followed the documentation provided by the React Navigation to implement but I have no luck to achieve what I expected and the output of the implementation looks so weird (You can find it on the 2nd picture). I also attached my code snippet at the bottom.
Also, the output looks like the Drawer navigator header is duplicated with the Stack Navigator.
Besides that, I am quite new to React Native. I hope someone makes me more clearer how the implementation should look like because I have come across few articles and websites, their solution does not work in my case.
P/S: Screen X is opened when one of item clicked from Screen C
import React, { Component } from 'react';
import {
Image,
Button,
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import { createDrawerNavigator, DrawerActions, DrawerItems } from 'react-navigation-drawer';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import HomeScreen from '../HomeScreen';
import ItemDetailScreen from '../ItemDetailScreen';
import ProfileScreen from '../ProfileScreen';
const navOptionsHandler = (navigation) => {
header: null
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ height: 150, backgroundColor: 'white', alignItems: 'center' }}>
<Image source={{ uri: 'https://example.com/logo.png' }} style={{
height: 120,
width: 120,
borderRadius: 60
}} />
</View>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const MyDrawerNavigator = createDrawerNavigator(
{
Home: {
screen: HomeScreen
},
Profile: {
screen: ProfileScreen
}
},
{
initialRouteName: "Home",
contentComponent: CustomDrawerComponent,
contentOptions: {
activeTintColor: 'orange'
}
}
);
const MyStackNavigator = createStackNavigator(
{
HomeA: {
screen: MyDrawerNavigator
},
ItemDetail: {
screen: ItemDetailScreen,
navigationOptions: navOptionsHandler
}
},
{
initialRouteName: "HomeA"
}
);
const AppContainer = createAppContainer(MyStackNavigator);
export default class StackNavigator extends Component {
render() {
return <AppContainer />;
}
}
Your drawer navigator is encapsulated by the stack navigator, which is why you have a double header.
What you need to do is to have the drawer navigator as your main navigator, and have your stack navigator as your profile screen, so it will be displayed as you click on "Profile" in your drawer navigator.
This should work:
const navOptionsHandler = navigation => {
null
}
const CustomDrawerComponent = props => (
<SafeAreaView style={{ flex: 1 }}>
<View
style={{ height: 150, backgroundColor: 'white', alignItems: 'center' }}
>
<Image
source={{ uri: 'https://example.com/logo.png' }}
style={{
height: 120,
width: 120,
borderRadius: 60,
}}
/>
</View>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const MyStackNavigator = createStackNavigator(
{
Profile: ProfileScreen,
ItemDetail: {
screen: ItemDetailScreen,
navigationOptions: navOptionsHandler,
},
},
{
initialRouteName: 'Profile',
},
)
const MyDrawerNavigator = createDrawerNavigator(
{
Home: HomeScreen,
ProfileStack: {
screen: MyStackNavigator,
navigationOptions: () => ({
title: 'Profile',
}),
}
},
{
initialRouteName: 'Home',
contentComponent: CustomDrawerComponent,
contentOptions: {
activeTintColor: 'orange',
},
},
)
const AppContainer = createAppContainer(MyDrawerNavigator)
export default class StackNavigator extends Component {
render() {
return <AppContainer />
}
}
By the way since you say you are only just starting using React Native, unless you have a specific reason to use React Navigation v4, you should probably use v5 instead as v4 will become obsolete one day or another.

Update username in navigation drawer when login with diffrent user in react native

I am showing username in drawernavigator, but when I logged out and logged in again with a different user, the username is not updating, it's showing old username.
I am also using didFocus Listener but it is also not working please help
import React, { Component } from 'react';
import { View, Image,Text, TouchableOpacity,MenuImage,navigation,AsyncStorage, Alert } from 'react-native';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import {
createDrawerNavigator,
createStackNavigator,
DrawerItems,
} from 'react-navigation';
import WalkThrow from '../pages/WalkThrow';
import Login from '../pages/Login';
import Register from '../pages/Register';
class NavigationDrawerStructure extends Component {
static propTypes = {
navigation: functionTypes.isRequired,
};
toggleDrawer = async() => {
this.props.navigationProps.openDrawer();
};
render() {
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
<Image
source={require('../assets/images/menu48.png')}
style={{ width: 25, height: 25, marginLeft: 15 }}
/>
</TouchableOpacity>
</View>
);
}
}
class NavigationImage extends Component {
toggleDrawer = async() => {
this.props.navigationProps.openDrawer();
};
render() {
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={this.toggleDrawer. bind(this)}>
<Image
source={require('../assets/images/user.png')}
style={{ width: 40, height: 40, marginRight:15 }}
/>
</TouchableOpacity>
</View>
);
}
}
class ShowUserName extends Component{
constructor(props) {
super(props);
this.state = {
getname:''
}
}
componentDidMount= async()=>{
let getname = await AsyncStorage.getItem('userName');
this.setState({getname:getname});
const { navigation } = this.props;
this.focusListener = navigation.addListener("didFocus", async() => {
let getname = await AsyncStorage.getItem('userName');
this.setState({getname:getname});
});
}
render() {
return (
<View>
<Text style={{color:'#fff',fontSize:23,padding:5}}>
{this.state.getname}
</Text>
</View>
);
}
}
const Logout= createStackNavigator({
Register:{
screen:Register,
navigationOptions:{
header: null,
},
},
Login: {
screen: Login,
navigationOptions:{
header: null,
}
},
ForgetPassword: {
screen: ForgetPassword,
navigationOptions:{
header: null,
}
},
initialRouteName: 'WalkThrow',
});
const Profile_StackNavigator = createStackNavigator({
Profile: {
initialRouteName: 'Profile',
screen:ChangeName,
navigationOptions: ({ navigation }) => ({
title: 'Profile',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#3598db',
shadowOpacity: 0,
elevation: 0,
},
headerTintColor: '#fff',
}),
}
});
const ChangePassword_StackNavigator = createStackNavigator({
ChangePassword: {
initialRouteName: 'WalkThrow',
screen:ChangePassword,
navigationOptions: ({ navigation }) => ({
title: 'Change Password',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#3598db',
shadowOpacity: 0,
elevation: 0,
},
headerTintColor: '#fff',
}),
},
});
const DashBoard_StackNavigator = createStackNavigator({
WalkThrow: {
screen: WalkThrow,
navigationOptions:{
header: null,
},
},
const DrawerContent = (props) => (
<View>
<View
style={{
backgroundColor: '#3598db',
height: 200,
alignItems: 'center',
justifyContent: 'center',
}}>
<Image
source={require('../assets/images/user.png')}
style={{ width:'36%', height: '50%' }}
/>
<ShowUserName/>
</View>
<DrawerItems {...props} />
</View>
)
export default createDrawerNavigator({
ChangePassword: {
screen: ChangePassword_StackNavigator,
initialRouteName: 'Logout',
navigationOptions: {
drawerLabel: 'Change Password',
drawerIcon: () => (
<Image
source={require('../assets/images/user48.png')}
style={{width: 25, height: 25, }}
/>
)
},
},
Logout: {
screen: Logout,
initialRouteName: 'Logout',
navigationOptions: {
drawerLabel: 'Logout',
drawerIcon: () => (
<Image
source={require('../assets/images/user48.png')}
style={{width: 25, height: 25,}}
/>
)
},
},
},
{
contentComponent: DrawerContent,
});
I am showing username in drawernavigator,but when i logged out and login again with different user the username is not updating,its showing old username.when different user login then show the username for those user
the issue is that this doesn't rerun because the drawer does not unmount
componentDidMount= async()=>{
let getname = await AsyncStorage.getItem('userName');
this.setState({getname:getname});
const { navigation } = this.props;
this.focusListener = navigation.addListener("didFocus", async() => {
let getname = await AsyncStorage.getItem('userName');
this.setState({getname:getname});
});
}
the bigger problem with the architecture of your app is that you' using asyncStorage as your state management it isa huge anti pattern and will make your app really slow and battery draining in the long run.
you have to use some sort of state management ie Context API or redux, then you get your userName straight form the global state it will make the app much faster and solve your problem and probably many others you are experiencing
then your render will look something like this without any need to to set the state again in a lifeCycle Method, you may also need a default depending where you declared the drawer
render() {
return (
<View>
<Text style={{color:'#fff',fontSize:23,padding:5}}>
{this.props.SOMEGLOBALCONTEXTHERE.username || ''}
</Text>
</View>
);
}

Drawers opens by default in react native

I am making a react native app which contains two navigator like below.
const drawerNavigator = createDrawerNavigator(
{
HomePage: { screen: Stack },
History: { screen: History },
Transactions: { screen: Transactions },
Profile: { screen: EditProfile },
Wallet: { screen: Wallet },
ResetPassword: { screen: ResetPassword }
},
{
contentComponent: props => <Drawer { ...props }
/>;
},
{
contentOptions: {
activeTintColor: '#e91e63',
}
});
const RootStack = createStackNavigator({
Splash: { screen: Splash },
Login: { screen: Login },
Register: { screen: Register },
ForgotPassword: { screen: ForgotPassword },
CreateProfile: { screen: CreateProfile },
UploadDocuments: { screen: UploadDocuments },
Home: { screen: drawerNavigator }
}, {
headerMode: 'none',
initialRouteName: 'Splash'
});
Now the problem is that when i logged in successfully then in goes to drawernavigator like this.
this.props.navigation.navigate("Home")
But the problem is that when it goes in stack then it opens drawer by default.How can i make drawer close by default in react native
the problem is that there are 2 routes with name 'Home', one in RootStack and one in drawerNavigator
so every time you navigate to 'Home' both routs get activated. Try changing the name in any one stack
**update for closing drawer
const parent = this.props.navigation.dangerouslyGetParent();
const isDrawerOpen = parent && parent.state && parent.state.isDrawerOpen;
if(isDrawerOpen)
this.props.navigation.closeDrawer();
put this in your componentDidMount()
**for showing data from async storage i did this
class homeDrawerComponent extends Component {
constructor(props) {
super(props);
this.state = {
user: null
};
}
async componentDidMount() {
let user = await appDataStorage.getUser();
await this.setState({ user: user });
}
render(){
const name = this.state.user?this.state.user.firstName+' '+this.state.user.lastName:'';
const email = this.state.user?this.state.user.email:'';
return (
<SafeAreaView>
<View
style={{ height: height * .22, justifyContent: 'flex-start', alignItems: 'flex-start', backgroundColor: 'white',paddingLeft:10,paddingTop:10 }} >
<Image
source={require('./components/images/sj-book-library-logo-drawer.png')}
style={{ width: width * .22, height: width * .25, borderRadius: 50 }} />
<Text style={{ fontWeight: 'bold', color: '#0094FFFF' }}>
{name}
</Text>
<Text style={{ fontWeight: 'bold', color: '#0094FFFF' }}>
{email}
</Text>
</View>
<ScrollView>
<DrawerItems {...this.props} />
</ScrollView>
</SafeAreaView>
)
}
}

How to navigate between screens from any js class that is not inside App.js in React Native

It's very easy to navigate from one screen to another that is inside App.js class. What I have done is made three classes : App.js, SearchList.js and Detail.js. But i am facing issue that how to navigate from searchList.js to Detail.js on click any view inside searchList.js class. Should i use StackNavigator again in searchList.js or declare all classes in App.js ?
App.js
import React from 'react';
import { Image,Button, View, Text ,StatusBar,StyleSheet,Platform,TouchableOpacity,ImageBackground,Picker,Alert,TouchableHighlight} from 'react-native';
import { StackNavigator,DrawerNavigator,DrawerItems } from 'react-navigation';
import {Constants} from "expo";
import SearchList from './classes/SearchList';
import Detail from './classes/Detail';
const DrawerContent = (props) => (
<View>
<View
style={{
backgroundColor: '#f50057',
height: 160,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text style={{ color: 'white', fontSize: 30 }}>
Header
</Text>
</View>
<DrawerItems {...props} />
</View>
)
class HomeScreen extends React.Component {
static navigationOptions = {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => (
<Image
source={require('./images/crown.png')}
style={[styles.icon, {tintColor: '#f50057'}]}
/>
),
};
constructor(){
super();
this.state={PickerValueHolder : ''}
}
GetSelectedPickerItem=()=>{
Alert.alert(this.state.PickerValueHolder);
}
render() {
return (
<ImageBackground source={require('./images/green.png')} style={styles.backgroundImage} >
<TouchableOpacity onPress={() =>this.props.navigation.navigate('DrawerOpen')}>
<Image
source={require('./images/menu-button.png')}
style={styles.imagesStyle}
/>
</TouchableOpacity>
<View style={styles.columnContainer}>
<TouchableHighlight style={styles.search} underlayColor='#fff' onPress={() => this.props.navigation.navigate('SearchList')}>
<Text style={styles.searchText}>Search Hotels</Text>
</TouchableHighlight>
</View>
</ImageBackground >
);
}
}
class DetailsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Button
title="Go to Details... again"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
backgroundImage: {
flex: 1,
width: null,
height: null,
marginTop: Constants.statusBarHeight,
},
search:{
marginTop:20,
paddingTop:15,
borderRadius:8,
borderColor: '#fff'
},
searchText:{
color:'#fff',
textAlign:'center',
}
// backgroundColor: '#ef473a', // app color
});
const HomeStack = StackNavigator({
Home: {
screen: HomeScreen,
navigationOptions: ({ navigation }) => ({
header: null,
})
},
SearchList: { screen: SearchList },
Detail: { screen: Detail},
});
const RootStack = DrawerNavigator(
{
Home: {
screen: HomeStack,
},
DetailsScreen: {
screen: DetailsScreen,
},
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
SearchList.js
import React, { Component } from 'react';
import { StyleSheet, Platform, View, ActivityIndicator, FlatList, Text, Image, Alert, YellowBox,ImageBackground } from 'react-native';
import { StackNavigator,} from 'react-navigation';
import Detail from './classes/Detail';
export default class SearchList extends Component {
constructor(props) {
super(props);
this.state = {isLoading: true}
YellowBox.ignoreWarnings([
'Warning: componentWillMount is deprecated',
'Warning: componentWillReceiveProps is deprecated',
]);
}
GetItem (flower_name) {
Alert.alert(flower_name);
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: .0,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
webCall=()=>{
return fetch('https://reactnativecode.000webhostapp.com/FlowersList.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount(){
this.webCall();
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator size="large" />
</View>
);
}
return (
<View style={styles.MainContainer}>
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) =>
<ImageBackground source= {{ uri: item.flower_image_url }} style={styles.imageView}
onPress={() => this.props.navigation.navigate('Detail')}>
</ImageBackground>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 5,
marginTop: Constants.statusBarHeight , //(Platform.OS === 'ios') ? 20 : 14,
},
imageView: {
width: '100%',
height: 220 ,
margin: 7,
borderRadius : 40,
},
});
const HomeStack = StackNavigator({
Detail: { screen: Detail},
});
export default class App extends React.Component {
render() {
return <HomeStack />;
}
}
Any help would be appreciable.
To navigate to any screen you need to have a navigation object. Navigation object can be provided in two ways
By declaring it in StackNavigator
By explicitly passing it as a prop to some other screen
If you use the first approach, and you need to navigate from SecondScreen to ThirdScreen, both of your screens should be declared in the StackNavigator first, only then navigation will be successful.
If you are using any trivial component ( such as a modal box ) to navigate to another screen, all you need to do is pass the navigation props (this.props.navigation) to the modal box component and use the props to navigate to another screen. The only requirement here being, this.props.navigation should be available in the class where the modal box component is loaded.
EDIT
As requested, here is the snippet
const App = StackNavigator({
FirstScreen: { screen: FirstScreen},
SecondScreen: { screen: SecondScreen},
ThirdScreen: { screen: ThirdScreen}
})
export default App;
In your SecondScreen, declare an object const { navigate } = this.props.navigation; and on a button click, use this object to navigate to another screen navigate("ThirdScreen");
Regarding the second approach, if your component is a modal, you can pass the navigate object as - <Modal navigation={navigate} /> and in the modal component you can use it as this.props.navigation("ThirdScreen");
Hope it clarifies now.
Support we have js named SecondScreen.js at the same directory level as App.js then we should import it like this in App.js
import SecondScreen from './SecondScreen';
It worked for me. Hope this helps to you too.
I think you are trying to implement the functionality of a stack navigator.
Go to React-Navigation-Docs. In stack navigator you can make stack of screens, and navigate from one to another. Inside index.js :
import { StackNavigator, TabNavigator } from "react-navigation";
import SplashScreen from "./src/screens/start/splash";
import LoginScreen from "./src/screens/start/login";
import DomainScreen from "./src/screens/start/domain";
const App = StackNavigator(
{
Splash: {
screen: SplashScreen,
},
Domain: {
screen: DomainScreen,
},
Login: {
screen: LoginScreen,
},
Tabs: {
screen: HomeTabs,
}
},
{
initialRouteName: "Splash",
}
);
AppRegistry.registerComponent("app_name", () => App);
then you can navigate to any of these screens using this.props.navigation.navigate("ScreenName")

Custom View as background for StackNavigator

I need use one image below stack navigator or something like this.
Into StackNavigator I can set backgroundColor, opacity (view style) etc. But no possibility to set one background image or custom view component. Also if set to each screen its not good for screen translation.
I was try to wrap like this:
<ImageBackground>
<MyStackNavigator/>
</ImageBackground/>
No results.
Can you help me? +1 for any try
I found a solution
Navigator:
const AuthStackNavigator = StackNavigator({
LANDING: {
screen: LandingScreen
},
SIGN_IN: {
screen: SignInScreen
},
{
mode: 'card',
cardStyle: { backgroundColor: 'transparent' },
transitionConfig: () => ({
containerStyle: {
backgroundColor: 'transparent',
}
}),
initialRouteName: 'LANDING',
}
);
Render:
render() {
return <ImageBackground
style={{
width: null,
height: null,
backgroundColor: 'transparent',
flex: 1,
}}
source={landing_background}
>
<AuthStackNavigator
ref='navigator'
/>
</ImageBackground>
}