passing parameter in react native drawer - react-native

When user login in LoginScreen.js I can get username, password, token.
To implement logout in CustomSidebarMenu.js, I need to pass those parameters from LoginScreen.js to CustomSidebarMenu.js (LoginScreen.js -> DrawerNavigationRoutes.js -> CustomSidebarMenu.js)
I checked that I implemented from LoginScreen.js to DrawerNaviagtionRoutes.js by using
alert(props.route.params.token)
in DrawerNavigatorRoutes.js
but I have no idea to pass parameter in
drawerContent={props => <CustomSidebarMenu {...props} />}>
here's my code
LoginScreen.js
import React, {useState, createRef} from 'react';
import {
StyleSheet,
TextInput,
View,
Text,
ScrollView,
Image,
Keyboard,
TouchableOpacity,
KeyboardAvoidingView,
} from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
import Loader from './Components/Loader';
const LoginScreen = ({navigation}) => {
const [userName, setUserName] = useState('');
const [userPassword, setUserPassword] = useState('');
const [loading, setLoading] = useState(false);
const [errortext, setErrortext] = useState('');
const emailInputRef = createRef();
const passwordInputRef = createRef();
const handleSubmitPress = () => {
setErrortext('');
if (!userName) {
alert('Please fill Username');
return;
}
if (!userPassword) {
alert('Please fill Password');
return;
}
setLoading(true);
fetch('http://localhost:8000/user/login/', {
method: 'POST',
//body: formBody,
headers: {
//Header Defination
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: userName,
password: userPassword,
})
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === 'success') {
navigation.replace('DrawerNavigationRoutes', {username:userName, password:userPassword, token:responseJson.token});
} else {
setErrortext(responseJson.error);
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
};
return (
<View style={styles.mainBody}>
<Loader loading={loading} />
<ScrollView
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
flex: 1,
justifyContent: 'center',
alignContent: 'center',
}}>
<View>
<KeyboardAvoidingView enabled>
<View style={{alignItems: 'center'}}>
<Image
source={require('../Image/techmate.png')}
style={{
width: '50%',
height: 100,
resizeMode: 'contain',
margin: 30,
}}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={(UserName) =>
setUserName(UserName)
}
placeholder="Enter Username"
placeholderTextColor="#8b9cb5"
autoCapitalize="none"
returnKeyType="next"
onSubmitEditing={() =>
emailInputRef.current && emailInputRef.current.focus()
}
underlineColorAndroid="#f000"
blurOnSubmit={false}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={(UserPassword) =>
setUserPassword(UserPassword)
}
placeholder="Enter Password" //12345
placeholderTextColor="#8b9cb5"
keyboardType="default"
ref={passwordInputRef}
onSubmitEditing={Keyboard.dismiss}
blurOnSubmit={false}
secureTextEntry={true}
underlineColorAndroid="#f000"
returnKeyType="next"
/>
</View>
{errortext != '' ? (
<Text style={styles.errorTextStyle}>
{errortext}
</Text>
) : null}
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={handleSubmitPress}>
<Text style={styles.buttonTextStyle}>LOGIN</Text>
</TouchableOpacity>
<Text
style={styles.registerTextStyle}
onPress={() => navigation.navigate('RegisterScreen')}>
New Here ? Register
</Text>
</KeyboardAvoidingView>
</View>
</ScrollView>
</View>
);
};
export default LoginScreen;
DrawerNavigationRoutes.js
import React from 'react';
// Import Navigators from React Navigation
import {createStackNavigator} from '#react-navigation/stack';
import {createDrawerNavigator} from '#react-navigation/drawer';
// Import Screens
import HomeScreen from './DrawerScreens/HomeScreen';
import CameraScreen from './DrawerScreens/CameraScreen';
import LedgerScreen from './DrawerScreens/LedgerScreen';
import RecommendScreen from './DrawerScreens/RecommendScreen';
import SettingsScreen from './DrawerScreens/SettingScreen';
import CustomSidebarMenu from './Components/CustomSidebarMenu';
import NavigationDrawerHeader from './Components/NavigationDrawerHeader';
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const HomeScreenStack = ({navigation}) => {
return (
<Stack.Navigator initialRouteName="HomeScreen">
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{
title: 'Home', //Set Header Title
headerLeft: () => (
<NavigationDrawerHeader navigationProps={navigation} />
),
headerStyle: {
backgroundColor: '#307ecc', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
</Stack.Navigator>
);
};
const CameraScreenStack = ({navigation}) => {
return (
<Stack.Navigator
initialRouteName="CameraScreen"
screenOptions={{
headerLeft: () => (
<NavigationDrawerHeader navigationProps={navigation} />
),
headerStyle: {
backgroundColor: '#307ecc', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}>
<Stack.Screen
name="CameraScreen"
component={CameraScreen}
options={{
title: 'Camera', //Set Header Title
}}
/>
</Stack.Navigator>
);
};
const LedgerScreenStack = ({navigation}) => {
return (
<Stack.Navigator
initialRouteName="LedgerScreen"
screenOptions={{
headerLeft: () => (
<NavigationDrawerHeader navigationProps={navigation} />
),
headerStyle: {
backgroundColor: '#307ecc', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}>
<Stack.Screen
name="LedgerScreen"
component={LedgerScreen}
options={{
title: 'Ledger', //Set Header Title
}}
/>
</Stack.Navigator>
);
};
const RecommendScreenStack = ({navigation}) => {
return (
<Stack.Navigator
initialRouteName="RecommendScreen"
screenOptions={{
headerLeft: () => (
<NavigationDrawerHeader navigationProps={navigation} />
),
headerStyle: {
backgroundColor: '#307ecc', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}>
<Stack.Screen
name="RecommendScreen"
component={SettingsScreen}
options={{
title: 'Recommend', //Set Header Title
}}
/>
</Stack.Navigator>
);
};
const SettingScreenStack = ({navigation}) => {
return (
<Stack.Navigator
initialRouteName="SettingsScreen"
screenOptions={{
headerLeft: () => (
<NavigationDrawerHeader navigationProps={navigation} />
),
headerStyle: {
backgroundColor: '#307ecc', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}>
<Stack.Screen
name="SettingsScreen"
component={SettingsScreen}
options={{
title: 'Settings', //Set Header Title
}}
/>
</Stack.Navigator>
);
};
const DrawerNavigatorRoutes = (props) => {
return (
<Drawer.Navigator
drawerContentOptions={{
activeTintColor: '#cee1f2',
color: '#cee1f2',
itemStyle: {marginVertical: 5, color: 'white'},
labelStyle: {
color: '#d8d8d8',
},
}}
screenOptions={{headerShown: false}}
drawerContent={props => <CustomSidebarMenu {...props} />}>
<Drawer.Screen
name="homeScreenStack"
options={{drawerLabel: 'Home Screen'}}
component={HomeScreenStack}
/>
<Drawer.Screen
name="cameraScreenStack"
options={{drawerLabel: 'Camera Screen'}}
component={CameraScreenStack}
/>
<Drawer.Screen
name="ledgerScreenStack"
options={{drawerLabel: 'Ledger Screen'}}
component={LedgerScreenStack}
/>
<Drawer.Screen
name="recommendScreenStack"
options={{drawerLabel: 'Recommend Screen'}}
component={RecommendScreenStack}
/>
<Drawer.Screen
name="settingScreenStack"
options={{drawerLabel: 'Setting Screen'}}
component={SettingScreenStack}
/>
</Drawer.Navigator>
);
};
export default DrawerNavigatorRoutes;
CustomSidebarMenu.js
import React from 'react';
import {View, Text, Alert, StyleSheet} from 'react-native';
import {
DrawerContentScrollView,
DrawerItemList,
DrawerItem,
} from '#react-navigation/drawer';
const CustomSidebarMenu = (props) => {
const logout = () => {
fetch('http://localhost:8000/user/logout/', {
method: 'POST',
headers: {
//Header Defination
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: props.route.params.token,
},
body: JSON.stringify({
username: props.route.params.username,
password: props.route.params.password,
})
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
//setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === 'success') {
props.navigation.replace('Auth');
} else {
setErrortext(responseJson.error);
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
}
return (
<View style={stylesSidebar.sideMenuContainer}>
<View style={stylesSidebar.profileHeader}>
<View style={stylesSidebar.profileHeaderPicCircle}>
<Text style={{fontSize: 25, color: '#307ecc'}}>
{'About React'.charAt(0)}
</Text>
</View>
<Text style={stylesSidebar.profileHeaderText}>AboutReact</Text>
</View>
<View style={stylesSidebar.profileHeaderLine} />
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
<DrawerItem
label={({color}) => <Text style={{color: '#d8d8d8'}}>Logout</Text>}
onPress={
//props.navigation.toggleDrawer();
logout
}
/>
</DrawerContentScrollView>
</View>
);
};
export default CustomSidebarMenu;

Related

How remove Login bottom tab navigator but still make it the first screen when I open the app?

I am using react native navigation. My idea is to put the login screen first and from there navigate to the "Wine Catalogue" route after login (I am using google authentication and all that works) via "navigation.navigate("UserInfo", { email, name, photoUrl })," that is the code in the login screen and it works fine but I don't want Login screen to have a bottom tab navigation (Like Wine Catalogue and user info), just the screen and when a user logs in it should transfer/navigate him to the "Wine Catalogue" screen. Can someone please tell me what am I missing?
Also how would I display the email, name, photoUrl that are forwarded from the login screen to UserInfo?
navigator.js:
import * as React from "react";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import { LoginScreen } from "../screens/LoginScreen";
import { WineCatalogue } from "../screens/WineCatalogue";
import { UserInfoSceen } from "../screens/UserInfoScreen";
import { createBottomTabNavigator } from "#react-navigation/bottom-tabs";
import Ionicons from "#expo/vector-icons/Ionicons";
const Stack = createStackNavigator();
export function MyStack() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Login">
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="WineCatalogue" component={WineCatalogue} />
<Stack.Screen name="UserInfo" component={UserInfoSceen} />
</Stack.Navigator>
</NavigationContainer>
);
}
const Tab = createBottomTabNavigator();
export function TabNavigator() {
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
if (route.name === "WineCatalogue") {
iconName = focused ? "wine" : "wine-outline";
} else if (route.name === "UserInfo") {
iconName = focused ? "person" : "person-outline";
}
return <Ionicons name={iconName} size={size} color={color} />;
},
tabBarActiveTintColor: "darkred",
tabBarInactiveTintColor: "gray",
})}
>
<Tab.Screen
name="Login"
component={LoginScreen}
options={{
headerTitle: "Login",
headerTitleStyle: {
fontWeight: "bold",
fontSize: 25,
paddingBottom: 5,
color: "white",
},
headerStyle: {
backgroundColor: "darkred",
shadowColor: "transparent",
height: 120,
},
title: "LOGIN",
tabBarStyle: {
paddingTop: 5,
},
}}
/>
<Tab.Screen
name="WineCatalogue"
component={WineCatalogue}
options={{
headerTitle: "Wine Catalogue",
headerTitleStyle: {
fontWeight: "bold",
fontSize: 25,
paddingBottom: 5,
color: "white",
},
headerStyle: {
backgroundColor: "darkred",
shadowColor: "transparent",
height: 120,
},
title: "WINE CATALOGUE",
tabBarStyle: {
paddingTop: 5,
},
}}
/>
<Tab.Screen
name="UserInfo"
component={UserInfoSceen}
options={{
headerTitle: "USER INFO",
headerTitleStyle: {
fontWeight: "bold",
fontSize: 25,
paddingBottom: 5,
color: "white",
},
headerStyle: {
backgroundColor: "darkred",
shadowColor: "transparent",
height: 120,
},
title: "USER INFO",
tabBarStyle: {
paddingTop: 5,
},
}}
/>
</Tab.Navigator>
</NavigationContainer>
);
}
LoginScreen.js
import React from "react";
import { View, Button, StyleSheet } from "react-native";
import * as Google from "expo-google-app-auth";
export function LoginScreen({ navigation }) {
const handleGoogleSignIn = () => {
const config = {
iosClientId:
"608924630924-37cv4o1pg812fa42a04ev4h7ppe6iii4.apps.googleusercontent.com",
androidClientId:
"608924630924-2al2brd2if6m7qj1vm4v5jbmcqab472b.apps.googleusercontent.com",
expoClientId:
"608924630924-f0jeg4heeid44ksa84fsqcimc90asl1v.apps.googleusercontent.com",
scopes: ["profile", "email"],
};
Google.logInAsync(config)
.then((result) => {
const { type, user } = result;
if (type == "success") {
const { email, name, photoUrl } = user;
console.log("Signin successfull");
setTimeout(
() => navigation.navigate("UserInfo", { email, name, photoUrl }),
1000
);
} else {
console.log("Siging not successfull");
}
})
.catch((error) => {
console.log(error);
});
};
return (
<View style={styles.screen}>
<View style={styles.buttonContainer}>
<Button
title="Google SignIn"
onPress={handleGoogleSignIn}
style={styles.button}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
buttonContainer: {
backgroundColor: "#1ecbe1",
},
button: {
color: "black",
width: 200,
height: 200,
},
});
The TabNavigator should be a screen of MyStack
Get the user from wherever your auth is.
<Stack.Navigator>
{user ? (
<Stack.Screen name="WineCatalogue" component={TabNavigator} />
<Stack.Screen name="UserInfo" component={UserInfoSceen} />
) : (
<Stack.Screen name="Login" component={LoginScreen} />
)}
</Stack.Navigator>

Hoisting react-navigation static navigationOptions

I have few class components, that uses react-navigation, when I'm wrapping class component to use HOC, the header dissappears, after doing some research, it seems I need to hoist the static navigationOptions = {}
My themeProvider
export const ThemeContextProvider = ({ children }) => {
const [themeID, setThemeID] = useState();
useEffect(() => {
(async () => {
const storedThemeID = await AsyncStorage.getItem(STORAGE_KEY);
if (storedThemeID) setThemeID(storedThemeID);
else setThemeID(THEMES[1].key);
})();
}, []);
return (
<ThemeContext.Provider value={{ themeID, setThemeID }}>
{!!themeID ? children : null}
</ThemeContext.Provider>
);
};
export function withTheme(Component) {
return props => {
const { themeID, setThemeID } = useContext(ThemeContext);
const getTheme = themeID => THEMES.find(theme => theme.key === themeID);
const setTheme = themeID => {
AsyncStorage.setItem(STORAGE_KEY, themeID);
setThemeID(themeID);
};
return (
<Component
{...props}
themes={THEMES}
theme={getTheme(themeID)}
setTheme={setTheme}
/>
);
};
hoistNonReactStatics(withTheme, HomeScreen); //I've tried this, but header still does not show up.
}
The component in question
export class HomeScreen extends Component {
static navigationOptions = ({ navigation }) => ({
title: 'Dashboard',
headerTintColor: 'white',
headerStyle: {
backgroundColor: 'red',
borderBottomWidth: 0,
},
headerLeft: (
<TouchableOpacity
style={{ paddingLeft: 15 }}
onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())}
>
<Feather name="arrow-left" size={24} color="#ffffff" />
</TouchableOpacity>
),
headerRight: (
<View style={{ flexDirection: 'row' }}>
</View>
),
});
componentDidMount() {
...
}
render() {
const { theme } = this.props;
console.log(theme);
return this.state.loading ? (
<ActivityIndicator
color="red"
size="large"
style={{ alignSelf: 'center', flex: 1 }}
/>
) : (
<View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
<View style={styles.container2}>
<TouchableOpacity>
<Feather
style={{ top: '60%', left: '28%' }}
name="plus"
size={32}
color="#ffffff"
onPress={this._openNewTaskModal}
/>
</TouchableOpacity>
<TouchableOpacity>
</TouchableOpacity>
</View>
<Feather
style={{ bottom: '5%', left: '85%' }}
name="calendar"
size={22}
color="#ffffff"
/>
<Feather
style={{ bottom: '9%', left: '8%' }}
name="home"
size={22}
color="#ffffff"
/>
</View>
);
}
}
export default withTheme(HomeScreen);
});
I also tried to export it as hoistNonReactStatics in the HomeScreen but no luck, what am I missing?
The solution was to use
export default hoistNonReactStatics(withTheme(HomeScreen), HomeScreen);

React Native drawer navigation screen header title and buttons

I am trying to add title and buttons to my home screen that is opened from drawer navigation. The following does not work(screen loads but no header) and i cant find documentation or sample on this that uses React Navigation v5. Did i miss something? This is the doc i am following.
<Drawer.Screen
name="Home"
component={HomeScreen}
title="Home Screen"
options={{
headerRight: () => (
<Button
onPress={() => alert("This is a button!")}
title="Info"
color="#fff"
/>
),
}}
/>
UPDATE: doing this on the screen didn't work as well.
const HomeScreen = (props) => {
return (
<Container>
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Home Screen2</Text>
</View>
</Container>
);
};
HomeScreen.navigationOptions = (props) => ({
title: "Home",
headerStyle: {
backgroundColor: "rgb(0, 145, 234)",
},
headerTintColor: "white",
headerTitleStyle: {
fontWeight: "bold",
color: "white",
},
});
export default HomeScreen;
From the option you put in, I guess you may want to add a Stack inside your Drawer navigation.
From the below example, when you go to the HomeStack, it will have a navigation bar and you can custom it using the option you put in.
(I also created a simple snack here: https://snack.expo.io/#gie3d/insane-ice-cream)
import React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer, DrawerActions } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { Ionicons } from '#expo/vector-icons';
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const HomeStack = () => (
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} options={({navigation}) => ({
title: "Home",
headerStyle: {
backgroundColor: "rgb(0, 145, 234)",
},
headerTintColor: "white",
headerTitleStyle: {
fontWeight: "bold",
color: "white",
},
headerLeft: () => (
<Ionicons
name={'md-menu'}
size={24}
style={{ marginLeft: 10 }}
onPress={() =>
navigation.dispatch(DrawerActions.toggleDrawer())
}
/>
),
})} />
</Stack.Navigator>
);
const Home = () => {
return (
<View>
<Text>This is Home</Text>
</View>
)}
export default () => {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="HomeStack">
<Drawer.Screen name="HomeStack" component={HomeStack} />
<Drawer.Screen name="HomeNoStack" component={Home} />
</Drawer.Navigator>
</NavigationContainer>
);
}
You need to create the button on your screen too, like this.
import React from "react";
import {Text, View} from 'react-native';
export default class News extends React.Component {
static navigationOptions = ({navigation}) => {
return {
//headerLeft: --- PUT HERE YOU CUSTOM BUTTON (Use navigation.goBack() in onPress)
headerLeft:(<HeaderBackButton size={20} onPress={()=>{navigation.navigate('Home')}} color="#fff" tintColor="#fff"/>),
headerStyle: {
backgroundColor: 'rgb(0, 145, 234)',
},
headerTintColor: 'white',
headerTitleStyle:
{
fontWeight: 'bold',
color:'white' ,
//paddingTop:"2%",
},
}
}
render() {
return (
<View>
<Text> Here Leave the News!! </Text>
</View>
);
}
}

React Native navigation v5 navigate to another screen from header

I am currently following a tutorial that has an older version of navigator. I have update the code to use v5. When moving to a screen the navigation function is available as in
const CreateScreen = ({ navigation }) => {
I am then able to set the navigation with
onPress={() => navigation.navigate("home")
Please can someone show me how to expose the navigation function within the createStackNavigator function
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import IndexScreen from "./src/screens/IndexScreens"
import ShowScreen from "./src/screens/ShowScreen"
import CreateScreen from "./src/screens/CreateScreen"
import EditScreen from "./src/screens/EditScreen"
import { Provider} from "./src/context/BlogContext"
import { Feather } from '#expo/vector-icons';
import { EvilIcons } from '#expo/vector-icons';
const Stack = createStackNavigator();
const MyStack = () => (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={IndexScreen}
options={{
title: 'Blog Posts',
headerTitleStyle: {
fontWeight: 'bold',
},
headerTitleAlign: "center",
headerRight: () => (
<TouchableOpacity style={{ marginRight: 15}} onPress={() => alert('Not working need to pass navigation function')}>
<Feather name="plus" size={30} />
</TouchableOpacity>
)
}}
/>
<Stack.Screen
name="Show"
component={ShowScreen}
options={{
title: 'Blog Post Detail',
headerTitleStyle: {
fontWeight: 'bold',
},
headerTitleAlign: "center",
headerRight: () => (
<TouchableOpacity style={{ marginRight: 15}} onPress={() => alert('Not working need to pass navigation function')}>
<EvilIcons name="pencil" size={35} />
</TouchableOpacity>
)
}}
/>
<Stack.Screen
name="Create"
component={CreateScreen}
options={{
title: 'Create A Blog Post',
headerTitleStyle: {
fontWeight: 'bold',
},
headerTitleAlign: "center"
}}
/>
<Stack.Screen
name="Edit"
component={EditScreen}
options={{
title: 'Edit Blog Post',
headerTitleStyle: {
fontWeight: 'bold',
},
headerTitleAlign: "center"
}}
/>
</Stack.Navigator>
);
const App = () => (
<NavigationContainer>
<MyStack />
</NavigationContainer>
);
export default () => {
return <Provider>
<App />
</Provider>
}
change your options
options={{
title: 'Blog Posts',
headerTitleStyle: {
fontWeight: 'bold',
},
headerTitleAlign: "center",
headerRight: () => (
<TouchableOpacity style={{ marginRight: 15}} onPress={() => alert('Not working need to pass navigation function')}>
<Feather name="plus" size={30} />
</TouchableOpacity>
)
}}
to
options={({ navigation }) => (
{
title: 'Blog Posts',
headerTitleStyle: {
fontWeight: 'bold',
},
headerTitleAlign: "center",
headerRight: () => (
<TouchableOpacity style={{ marginRight: 15}} onPress={() => navigation.navigate("Show")}>
<Feather name="plus" size={30} />
</TouchableOpacity>
)
})}
Do the same with the options in Show stack screen.
Hope this helps!
Replace navigation.navigate("Show") with navigation.navigate("Create")

Passing this.state into static function

I am trying to set the headerTitle in the header bar to be the username of the logged in user: this.state.username. However, when I try to set navigationOptions to a function, I am unable to pass in the current state.
What would be the best way to set the headerTitle inside the static navigationOptions? I believe that navigationOptions must remain static, otherwise nothing will be displayed.
class profile extends React.Component {
static navigationOptions =
{
headerTitle: this.state.username
};
const TabStack = createBottomTabNavigator(
{
Home: {
screen: home,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="home" size={25} style={{ color: tintColor }} />
),
},
},
Explore: {
screen: explore,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="search" size={25} style={{ color: tintColor }} />
),
}
},
Profile: {
screen: profile,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="person" size={25} style={{ color: tintColor }} />
),
}
},
Create: {
screen: createCompetition,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="add" size={25} style={{ color: tintColor }} />
),
}
},
Payment: {
screen: payment,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="attach-money" size={25} style={{ color: tintColor }} />
),
title: 'Payment',
}
}
},
{
tabBarOptions: {
showIcon: true,
showLabel: false,
activeTintColor: 'black',
style: { backgroundColor: 'white', }
},
},
)
TabStack.navigationOptions = ({ navigation, screenProps }) => {
const childOptions = getActiveChildNavigationOptions(navigation, screenProps)
return {
title: childOptions.title,
headerLeft: childOptions.headerLeft,
headerRight: childOptions.headerRight,
}
}
So instead of using react navigation Header ive disabled it and used my own cutsom,
This is my Header.js :
import React, {Fragment, Component} from 'react';
import {View, Text, TouchableOpacity, Image, SafeAreaView} from 'react-native';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import {headerStyles} from '../style/headerStyles';
export default class Header extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<View
style={{
flexDirection: 'row',
paddingBottom: hp('3.125%'),
justifyContent: 'space-between',
alignItems: 'center',
}}>
<View style={{opacity: 0}}>
<Image source={require('../assets/images/crossIcon.png')} />
</View>
<View style={{flexShrink: 1}}>
<Text style={headerStyles.headerText}>{this.props.title}</Text>
</View>
<View style={{left: -20, paddingLeft: 10, marginLeft: 10}}>
<TouchableOpacity
style={headerStyles.imageView}
onPress={() => this.props.navigation.goBack()}>
<Image
style={{height: 15, width: 15}}
source={require('../assets/images/crossIcon.png')}
/>
</TouchableOpacity>
</View>
</View>
);
}
}
and you can import in any component like :
import Header from '../components/Header';
return(
<Header title={this.state.userName} navigation={this.props.navigation} />
)
With this you have enough power to do anything you want with header.
Hope it helps. feel free for doubts.
I assume you are using react-navigation, I suggest you set a navigation param in your component and then get the param in the navigationOptions.
after login do this:
navigation.setParams({ headerTitle: this.state.userName})
and then inside your navigationOptions where you already have navigation:
return { title: navigation.getParam('headerTitle') }