How to make a custom HeaderTitle in React Navigation Stacknavigator? - react-native

Everytime i try to set a custom header in stacknavigation the error appears: "cant find variable View". When i replace the component with just a text, it works.
Error appears everytime i use the class "LogoTitle" for the headerTitel
tryied to use a const insted of a class, but dosent worked
const TabNavigation = createMaterialTopTabNavigator({
AllChats: { screen: AllChatsScreen,
navigationOptions: {
tabBarLabel: "Chats",}}});
class LogoTitle extends React.Component {
render() {
return (
<Image
source={require('./spiro.jpg')}
style={{ width: 30, height: 30 }}/>);}}
const SignedInn = createStackNavigator({
TabNavigation: {
screen: TabNavigation,
},},{
navigationOptions: {
headerTitle: <LogoTitle/>}})
export const createRootNavigator = (signedIn = false) => {
return createSwitchNavigator(
{
SignedIn: {
screen: SignedInn}});};

you need to use header instead of headerTitle to be able to use View
const SignedIn = createStackNavigator ({
TabNavigation:{screen: TabNavigation,
navigationOptions: ({navigation}) => ({
header: <LogoTitle navigation= {navigation} />,
})
},
})

Related

How to properly stack nested navigators within an App Container?

I currently have an AppContainer which consists of a bottom tab navigator and currently one more navigation set for Profile settings. I am trying to understand how to properly arrange everything, specifically how to nest navigation in one tab Profile so I can access two other pages QrCode and EditAccount each through two buttons. How do I achieve the below output? I believe I have to nest profile navigation somehow.
MY TABS BELOW
Home
Queue
Profile
:in here i have two other pages i can access QRCode and EditAccounts
App.js
const bottomTabNavigator = createBottomTabNavigator(
{
Home: {
screen: Home,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="home" size={25} color={tintColor} />
)
}
},
Queue: {
screen: Queue,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="comments" size={25} color={tintColor} />
)
}
},
Profile: {
screen: Profile,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<Icon name="user" size={25} color={tintColor} />
)
}
}
})
const navigationOptions = ({ navigation }) => {
return {
headerTitle: 'hello',
headerStyle: {
height: '45%',
backgroundColor: 'black'
},
headerTintColor: 'white',
headerLeft: (
<TouchableWithoutFeedback
style={{ /* Put your style here */}}
onPress={() => navigation.goBack()} >
<Ionicons name="ios-arrow-dropleft" size={32} color="white" />
</TouchableWithoutFeedback>
)
}
}
const ProfileNavigator = createStackNavigator({
//Profile: { screen: Profile},
QR: { screen: GenerateQR, navigationOptions },
Profile: { screen: Profile },
EditAccount: { screen: EditAccount, navigationOptions }
});
const AppNavigator = createSwitchNavigator({
tabs: bottomTabNavigator,
profile: ProfileNavigator
})
const AppContainer = createAppContainer(AppNavigator);
After Applying Answer
The solution offers works as needed with the code below:
const navigationOptions = ({ navigation }) => {
return {
headerTitle: 'hello',
headerStyle: {
height: '45%',
backgroundColor: 'black'
},
headerTintColor: 'white',
headerLeft: (
<TouchableWithoutFeedback
style={{ /* Put your style here */}}
onPress={() => navigation.goBack()} >
<Ionicons name="ios-arrow-dropleft" size={32} color="white" />
</TouchableWithoutFeedback>
)
}
}
const ProfileNavigator = createStackNavigator({
Profile: { screen: Profile},
QR: { screen: GenerateQR, navigationOptions },
EditAccount: { screen: EditAccount, navigationOptions }
});
//ADDED
ProfileNavigator.navigationOptions = () => {
const navigationOptions = {
header: null,
headerMode: 'none',
};
return navigationOptions;
};
const AppNavigator = createSwitchNavigator({
tabs: bottomTabNavigator,
profile: ProfileNavigator
})
const AppContainer = createAppContainer(AppNavigator);
The only issue is I am unsure how to port over the header options to the tabs in the in the bottomTabNavigator. I have a custom component in place for the profile page that makes it look like this (black bar with button icon for Profile):
I can then navigate to the EditAccounts by pressing on the user icon. But when I navigate back from EditAccounts back to profile, the page renders with the navigationOptions header like so:
How do I apply this properly so I can lean simply on the navigationOptions header and push a custom name onto it (get rid of my custom component in that case)?
There are 2 cases.
If you want to keep tabs when accessing QR or EditAccount
const BottomTabNavigator = createBottomTabNavigator({
...
Profile: {
screen: ProfileNavigator,
}
})
const ProfileNavigator = createStackNavigator({
Profile: { screen: Profile},
QR: { screen: GenerateQR, navigationOptions },
EditAccount: { screen: EditAccount, navigationOptions }
});
ProfileNavigator.navigationOptions = () => {
const navigationOptions = {
header: null,
headerMode: 'none',
};
return navigationOptions;
};
const AppContainer = createAppContainer(BottomTabNavigator);
If you don't want to keep tabs
const BottomTabNavigator = createBottomTabNavigator({
...
Profile: {
screen: Profile,
}
})
const AppNavigator = createStackNavigator({
Tabs: BottomTabNavigator,
QR: { screen: GenerateQR, navigationOptions },
EditAccount: { screen: EditAccount, navigationOptions }
})
const AppContainer = createAppContainer(AppNavigator);
UPDATED:
Add navigationOptions to ProfileNavigator to remove header
ProfileNavigator.navigationOptions = () => {
const navigationOptions = {
header: null,
headerMode: 'none',
};
return navigationOptions;
};

Dynamically change header title in react native navigation

For a school assignment we're creating an app in react native with react navigation and redux. Because all of us are new to react we have an issue we are unable to resolve.
We want to change the title of the header when a certain button is clicked. The first time we click a button it changes the header title just fine. The problem arrises when we press a different button, the header doesn't change. Note that no matter what option we choose, we always go to the same screen.
import React from 'react';
import { createStackNavigator, createAppContainer, createDrawerNavigator } from 'react-navigation';
import {connect} from 'react-redux';
import { store } from '#redux/MyStore';
import { Ionicons } from '#expo/vector-icons';
import ScannerScreen from '#screens/ContactScreen';
import EventsScreen from '#screens/ListScreen';
const ContactStack = createStackNavigator({
Contact: {
screen: ContactScreen,
navigationOptions: ({navigation}) => ({
headerStyle: {backgroundColor: '#fa8231'},
headerTitleStyle: {fontSize: 18},
title: store.getState().setupState.title,
headerLeft: <Ionicons
name="md-menu" style={{marginLeft:10}}
size={28}
onPress={() => navigation.toggleDrawer()} /> //menu button
})
}
});
// Code to create stack for the ListStack
const DrawerStack = createDrawerNavigator({
Contact: ContactStack,
List: ListStack
});
const PrimaryNavigation = createStackNavigator({
ListStack: {
screen: ListStack,
navigationOptions: {
header: null,
},
},
DrawerStack: {
screen: DrawerStack,
navigationOptions: {
header: null,
},
},
},
{
initialRouteName: 'ListStack',
});
const AppContainer = createAppContainer(PrimaryNavigation);
class AppNavigation extends React.Component {
render() {
return <AppContainer/>
}
}
export default (AppNavigation)
We did get it working when we put the title bar in the DrawerNavigator, but since we want the Drawer in from of the header that is not an option. My speculation is that the stack is created once with a certain title and never gets updated when switching screens using the DrawerNavigator but we have no clue how to fix that.
Thanks in advance!
From what I understand you need to change the title when a screen is loaded in stack.So you could use some like:
class ScreenInContactStack extends React.Component{
//Constryctor
static navigationOptions = ({navigation}) => ({
title: (navigation.state.params || {}).title || 'Chat! ',
});
//Remaining Logic
}
and while calling
this.props.navigation.navigate('ScreenInContactStack', {title: yourTitle + ' ',});
Don't know why but the Appbar condense the title to like yourTi.. to avoid this add a space to the title.
Try this:
map title as a prop to force ContactStack to re-render whenever it changes
class ContactStack extends React.Component {
render() {
const { title } = this.props.setupState;
const Stack = createStackNavigator({
Contact: {
screen: ContactScreen,
navigationOptions: ({navigation}) => ({
headerStyle: {backgroundColor: '#fa8231'},
headerTitleStyle: {fontSize: 18},
title,
headerLeft: <Ionicons
name="md-menu" style={{marginLeft:10}}
size={28}
onPress={() => navigation.toggleDrawer()} /> //menu button
})
}
});
return <Stack />;
}
}
const mapStateToProps = ({ setupState }) => ({setupState});
export default connect(mapStateToProps)(ContactStack);

How to add header bar when using createBottomTabNavigator?

I'm trying to add a constant Header bar to my screen (all screens, similar to this example) with basic functionality (menu button, and a back button), but I'm having trouble finding a way to do this when using createBottomTabNavigator. I haven't seen anything saying this isn't possible, so if I'm making a design mistake, do let me know.
Here is my minimal foobar example (it runs):
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { createBottomTabNavigator } from 'react-navigation';
import Ionicons from 'react-native-vector-icons/Ionicons';
class ScreenA extends React.Component {
constructor(props) {
super(props);
this.state = {
screenName: 'Screen A'
}
}
render() {
return (
<View
style={styles.container}
>
<Text>{this.state.screenName}</Text>
</View>
);
}
};
class ScreenB extends React.Component {
constructor(props) {
super(props);
this.state = {
screenName: 'Screen B'
}
}
render() {
return (
<View
style={styles.container}
>
<Text>{this.state.screenName}</Text>
</View>
);
}
};
const BottomTabNav = createBottomTabNavigator(
{
ScreenA: {
screen: ScreenA,
navigationOptions: {
title: '',
tabBarIcon: ({ focused, tintColor }) => {
return <Ionicons
name={ focused ? 'ios-card' : 'ios-card-outline' }
size={30}
style={{ marginTop: 6 }}
/>;
},
}
},
ScreenB: {
screen: ScreenB,
navigationOptions: {
title: '',
tabBarIcon: ({ focused, tintColor }) => {
return <Ionicons
name={ focused ? 'ios-chatbubbles' : 'ios-chatbubbles-outline' }
size={30}
style={{ marginTop: 6 }}
/>;
},
},
}
},
{
initialRouteName: 'ScreenA',
}
);
export default class App extends React.Component {
render() {
return (
<BottomTabNav />
);
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Apologies for not including a Snack link, but I'm having issues with dependencies when trying to build the demo.
You need your screens to be stack navigators which you then can add in your tab navigator. The "defaultNavigationOptions" are your navigationOptions for the header and the navigationOptions in the code snippet corresponds for the BottomTabNavigator options.
You can read more about this here: https://reactnavigation.org/docs/en/navigation-options-resolution.html
const StackA = createStackNavigator({ ScreenA },
{
defaultNavigationOptions: (navigationOptions),
navigationOptions: {
tabBarLabel: 'Screen A',
},
});
const StackB = createStackNavigator({ScreenA},
{
defaultNavigationOptions: (navigationOptions),
navigationOptions: {
tabBarLabel: 'Screen B',
},
});
const tabNavigator = createBottomTabNavigator({StackA, StackB});
only createStackNavigator has its own header so you have to wrap whatever you want in it, according to your question there is two answers to this,
put the createBottomTabNaviagator in a parent createStackNavigator and access the createBottomTabNavigator children routeName and assign it to the parent createStackNavigator header
const BottomTabNav = createBottomTabNavigator({
FirstScreen: ScreenA,
SecondScreen: ScreenB,
});
BottomTabNav.navigationOptions = ({ navigation }) => {
// By default routeName will come from the BottomTabNav,
// but here we can access the children screens
// and give the parent ParentStack that routeName
const { routeName } = navigation.state.routes[navigation.state.index];
// You can do whatever you like here to pick the title based on the route name
const headerTitle = routeName;
return {
headerTitle,
};
};
const ParentStack = createStackNavigator({
Home: BottomTabNav,
AnotherScreen: AnotherScreen,
});
put the child screens in a createStackNavigator so that every child will have its own header
const ScreenA = createStackNavigator({
FirstScreen: ScreenA,
/* other routes here */
});
const ScreenB = createStackNavigator({
SecondScreen: ScreenB,
/* other routes here */
});
const BottomTabNav = createBottomTabNavigator({
FirstScreen: ScreenA,
SecondScreen: ScreenB,
});

How to change screen using stackNavigation in React Native?

I have one screen which in header consists button to go to another screen.
I have already model here, but it doesn't work: As shown below I want to change the screen from RecipeList to NewRecipeForm using Button in header
const AppStackNavigator = createStackNavigator({
List: {
screen: RecipesList,
navigationOptions: {
title:'RecipesList',
headerLeft: (
<Button onPress={()=>this.props.navigation.navigate('NewRecipeForm')}>
<Text>+</Text>
</Button>
)
}},
NewRecipeForm: {screen: CreateRecipeForm,
navigationOptions: {title:'Add new recipe'}},
Details: {screen: RecipesDetails, navigationOptions: {title:'RecipeDetails'}},
export default class App extends React.Component {
render() {
return <AppStackNavigator initialRouteName='List' />;
}
}
I hope that you will help me with solution
You may use your stack navigator as like below, you can able to destructure your navigation property while giving your navigationOptions property as well in the createStackNavigator itself
const AppStackNavigator = createStackNavigator({
List: {
screen: RecipesList,
navigationOptions: ({navigation}) => { //destructure the navigation property here
return {
title: 'RecipesList',
headerLeft: (
<Button onPress={() => navigation.navigate('NewRecipeForm')}>
<Text>+</Text>
</Button>
)
}
}
},
NewRecipeForm: {
screen: CreateRecipeForm,
navigationOptions: { title: 'Add new recipe' }
},
Details: { screen: RecipesDetails, navigationOptions: { title: 'RecipeDetails' } }
});
You cannot access the props of your component in headerLeft, but you can directly use the navigation like this :
<Button onPress={()=> navigation.navigate('NewRecipeForm')}>
You can use following code inside your RecipesList Component instead of having it inside createStackNavigator(). See this Snack for full implementation.
static navigationOptions = ({ navigation }) => {
return {
headerTitle: "RecipesList",
headerLeft: (
<Button
onPress={() => navigation.navigate('NewRecipeForm')}
title="+"
/>
),
};
};

Cannot read property 'navigation' of undefined

I'm trying to navigate with NavigationActions, but for some reason it won't navigate.
I'm trying to move from LoginScreen to HomeScreen.
loginscreen:
constructor(props){
super(props)
this.state = {
email: '',
password: '',
status: '',
}
this.handlePress = this.handlePress.bind(this)
}
handlePress(){
firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(firebaseUser){
//Success, move to homepage.
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Home'})
]
})
this.props.navigation.dispatch(resetAction) <-- SAYS NAVIGATION IS UNDEFINED
}).catch(function(error){
//Failed to log in, print error.
console.log(error)
});
}
this is where I call handlePress:
<TouchableOpacity style={styles.logBtn} onPress={()=>this.handlePress()}>
<Text style={styles.logTxt}>
Login
</Text>
</TouchableOpacity>
This is 'navigation'(in render method, loginscreen):
const { navigation } = this.props.navigation;
this is app.js where I set the navigation:
import React from 'react';
import { AppRegistry } from 'react-native';
import { StackNavigator, TabNavigator } from 'react-navigation';
import Ionicons from 'react-native-vector-icons/Ionicons';
import LoginScreen from './app/screens/LoginScreen';
import RegisterScreen from './app/screens/RegisterScreen';
import HomeScreen from './app/screens/HomeScreen';
import FriendsScreen from './app/screens/FriendsScreen';
const Stylelist = StackNavigator({
Login:{
screen: LoginScreen,
navigationOptions: ({navigation}) =>({
header: null,
}),
},
Register:{
screen: RegisterScreen,
navigationOptions: ({navigation}) =>({
header: null,
}),
},
Home:{
screen: TabNavigator({
Home: {
screen: HomeScreen,
navigationOptions: ({ navigation }) => ({
title: 'Home',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-home' : 'ios-home-outline'}
size={26}
style={{ color: tintColor }}
/>
)
}),
},
Friends: {
screen: FriendsScreen,
navigationOptions: ({ navigation }) => ({
title: 'Friends',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-people' : 'ios-people-outline'}
size={26}
style={{ color: tintColor }}
/>
)
}),
},
}),
navigationOptions: ({ navigation }) => ({
title: 'Home',
headerStyle: {backgroundColor: "#553A91"},
headerTitleStyle: {color: "#FFFFFF"},
}),
}
});
export default Stylelist;
I tried to log the error from the 'catch' and I get this error:
Cannot read property 'navigation' of undefined
How can I fix it?
It should be
const { navigate} = this.props.navigation;
or
const { navigation } = this.props;
Actually, what you get in props is navigation object, which has navigate method in it.And what you were doing was
const { navigation } = this.props.navigation;
This gets evaluates to
this.props.navigation.navigation
It says look for navigation property inside navigation object, which actually is not present, hence giving undefined. I hope this clears your doubt.
I had this problem too.
Of course I had used setTimeout. There may be someone who has this problem, so it's a good reminder.
only use let that = this;
componentDidMount() {
let that = this ;
setTimeout(function () {
let toHome = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({routeName: 'MainScreen'})]
});
that.props.navigation.dispatch(toHome);
},3000);
}
Make sure your function is bind with this.
onPress={()=>this.handlePress()}
instead
onPress={()=>this.handlePress.bind(this)}