ReferenceError: Can't find variable: navigation [React Native] - javascript

Good day. I'm quite new to React Native. I am using the react-native-app-intro-slider for the app's intro/welcome screens. The intention is to then navigate to the Login Screen once the user is done or once they press the skip button.
Below is the code I have implemented in the OnboardingScreen. I am however getting an error with regards to the navigation.
import {
StyleSheet,
View,
Text,
Image,
StatusBar
} from 'react-native';
import AppNavigator from '../navigation/Screens';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import AppIntroSlider from 'react-native-app-intro-slider';
import Onboarding from 'react-native-onboarding-swiper';
import LoginScreen from '../screens/auth/LoginScreen';
const data = [
{
title: 'Header 1',
text: 'Description.\nSay something cool',
image: require('../assets/images/Slider_1.png'),
bg: '#ffffff',
},
{
title: 'Header 2',
text: 'Description.\nSay something cool',
image: require('../assets/images/Slider_2.png'),
bg: '#ffffff',
},
{
title: 'Header 3',
text: 'Description.\nSay something cool',
image: require('../assets/images/Slider_3.png'),
bg: '#ffffff',
},
];
const styles = StyleSheet.create({
slide: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
},
image: {
width: 320,
height: 320,
marginVertical: 32,
},
text: {
fontSize: 20,
color: '#000000',
textAlign: 'center',
},
title: {
fontSize: 30,
fontWeight: 'bold',
color: '#000000',
textAlign: 'center',
},
dotStyle: {
backgroundColor: '#000'
},
});
const Stack = createStackNavigator();
function Root() {
return (
<Stack.Navigator>
<Stack.Screen name="Login" component={LoginScreen} />
</Stack.Navigator>
);
}
export default class OnboardingScreen extends Component {
constructor(props) {
super(props);
this.state = {
showRealApp: false,
//To show the main page of the app
};
}
_onDone = () => {
navigation.navigate('Root', {
screen: 'LoginScreen'
});
//this.props.navigation.navigate('LoginScreen');
//this.setState({ showRealApp: true });
};
_onSkip = () => {
this.setState({ showRealApp: true });
};
_renderItem = ({item}) => {
return (
<View
style={[
styles.slide,
{
backgroundColor: item.bg,
},
]}>
<Text style={styles.title}>{item.title}</Text>
<Image source={item.image} style={styles.image} />
<Text style={styles.text}>{item.text}</Text>
</View>
);
};
_keyExtractor = (item) => item.title;
render() {
return (
<View style={{flex: 1}}>
<StatusBar translucent backgroundColor="transparent" />
<AppIntroSlider
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
bottomButton
showPrevButton
onDone={this._onDone}
showSkipButton={true}
onSkip={this._onSkip}
data={data}
/>
</View>
);
}
}
Navigation error

There are various mistakes you are doing here. First, I highly recommend you to structure your RN project in a way that it matches your needs, I won't talk a lot about this but I can give you a heads up. Usually, you have a separete folder/file with the route for your app, so move all your code related to react-navigation there. Once moved, you have to create a new stack that contains your welcome screen. So, it may look like:
const AppContainer = () => (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Intro" component={OnBoardingScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
</Stack.Navigator>
</NavigationContainer>
)
export default AppContainer
In the above code we are introducing a new stack that will be taken as the first screen to be reached. Why is this needed? You need to tell somehow to react-navigation the screens you are using in order to navigate to them. Once added the stack, you will have access to the navigation prop. There is another change here, you have to change your App.js file with the new component we are exporting from the above code which will be the root for the project. Once you have done with this, then you can use your _onDone method like this:
_onDone = () => {
/* use the name you used for the stack.
Also, you don't need to specify the screen
for this use case since you are not nesting
the navigators */
this.props.navigation.navigate('Intro');
};
And that's all. Basically, you needed to add a new stack with your OnBoardingScreen and start using the navigation prop

Related

Calling useNavigation hook from TouchableOpacity inside a DrawerNavigator from react-navigation pkg throwing error, full source on question body

I'm learning react and react-native last 4 days because need build an mobile app and having the following problem when coding a react-native app:
After some research I found a way to embed a TouchableOpacity inside the top bar of DrawerNavigator, just after the hamburger button and it works giving me an alert.
The problem comes when I try to replace the alert with a call to useNavigation().navigate('Login'); from inside it onPress attribute, it throw the error below.
I want mirror the behavior of menu item on the TouchableOpacity doing the navigation.
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem., js engine: hermes
info Reloading app...
The full source follow as:
import * as React from 'react';
import { Button, Image, StyleSheet, Text, TouchableOpacity, View, Alert } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import {
createDrawerNavigator,
DrawerContentScrollView,
DrawerItemList,
} from '#react-navigation/drawer';
// https://reactnavigation.org/docs/use-navigation/
import { useNavigation } from '#react-navigation/native';
const getScreenCtx = content => {
return (<View style={stl.boxCtx}>{content}</View>);
}
const Home = ({ navigation }) => {
return ( getScreenCtx(<Text style={stl.boxDescr}>Home</Text>) );
}
const Login = ({ navigation }) => {
return ( getScreenCtx(<Text style={stl.boxDescr}>Login</Text>) );
}
const Logout = ({ navigation }) => {
return ( getScreenCtx(<Text style={stl.boxDescr}>Logout</Text>) );
}
const navToLogin = () => {
useNavigation().navigate('Login');
}
const NestedTabBar = props => {
return (
<>
<TouchableOpacity
style={stl.itemNav}
onPress={
() => {
//Alert.alert('NavigateToLogin');
navToLogin();
}
} >
<Text>[NavigateToLogin]</Text>
</TouchableOpacity>
</>
);
}
const ContentTopWideHamburgBar = props => {
return <NestedTabBar />;// <Text style={stl.hamburgBar}>ContentTopHamburgBar</Text>
}
const ContentColapsibleSideBarMenuHeader = props => {
return <Text style={stl.sideMenuHeader}>SideBarMenuHeader</Text>
}
const ContentColapsibleSideBarMenuFooter = props => {
return <Text style={stl.sideMenuFooter}>SideBarMenuFooter</Text>
}
const ContentColapsibleSideBarMenu = props => {
return (
<View style={stl.sideBarMenu}>
<DrawerContentScrollView {...props}>
<ContentColapsibleSideBarMenuHeader/>
<DrawerItemList {...props} />
</DrawerContentScrollView>
<ContentColapsibleSideBarMenuFooter/>
</View>
);
}
const Drawer = createDrawerNavigator();
const ContentItensNavigationRouteMap = () => {
return (
<>
<Drawer.Screen component={Home} name='Home' />
<Drawer.Screen component={Login} name='Login' />
<Drawer.Screen component={Logout} name='Logout' />
</>
);
}
const DrawerNavigator = () => {
return (
<Drawer.Navigator
screenOptions={
{
headerStyle: { backgroundColor: 'magenta', },
headerTintColor: 'white', // hamburg color
headerTitleStyle: { fontWeight: 'bold', },
headerTitle: (props) => <ContentTopWideHamburgBar {...props} />
}
}
contentOptions={
{
activeTintColor: 'red',
activeBackgroundColor: 'red',
inactiveTintColor: 'red',
inactiveBackgroundColor: 'red',
}
}
drawerContent={props => <ContentColapsibleSideBarMenu {...props} />} >
{ContentItensNavigationRouteMap()}
</Drawer.Navigator>
);
};
export default function ShellNavigator() {
return (
<NavigationContainer>
<DrawerNavigator />
</NavigationContainer>
);
}
const stl = StyleSheet.create({
boxDescr: {
fontSize: 30,
margin: 10,
padding:10,
backgroundColor: 'lightblue',
color: 'red',
},
boxCtx:{
display: 'flex',
flex: 1,
fontSize: 30,
margin: 0,
backgroundColor: 'yellow',
},
hamburgBar: {
fontSize: 20,
margin: 10,
backgroundColor: 'pink',
},
sideMenuHeader: {
fontSize: 20,
margin: 10,
backgroundColor: 'blueviolet',
},
sideMenuFooter: {
fontSize: 20,
margin: 10,
backgroundColor: 'purple',
},
sideBarMenu: {
flex: 1,
fontSize: 20,
margin: 10,
backgroundColor: 'greenyellow',
},
itemNav: {
fontSize: 40,
padding: 10,
backgroundColor: 'red',
},
});
Here navToLogin is a stand alone function, not in a Functional component. Hooks need to be in a functional component to use. The bellow code should work which navToLogin move the function inside a functional component.
const NestedTabBar = props => {
const navigation = useNavigation();
const navToLogin = () => {
navigation.navigate('Login');
}
return (
<>
<TouchableOpacity
style={stl.itemNav}
onPress={
() => {
//Alert.alert('NavigateToLogin');
navToLogin();
}
} >
<Text>[NavigateToLogin]</Text>
</TouchableOpacity>
</>
);
}

Undefined is not an object (evaluating 'this.props.navigation.navigate') on React Native

I am currently working on my first react native project using Expo and I have a problem between the screens navigation where I get " undefined is not an object (evaluating 'this.props.navigation.navigate') ". I want to know what is actually the problem and how can I fix it. Thank you.
Here is the code for the screen where there is a navigation problem :
import {
StyleSheet,
Text,
View,
Button,
Date,
KeyboardAvoidingView,
} from "react-native";
import t from "tcomb-form-native";
import moment from "moment";
const Form = t.form.Form;
const User = t.struct({
Surname: t.String,
Name: t.String,
Birthday: t.Date,
});
const options = {
fields: {
Surname: {
label: "Surname",
},
Name: {
label: "Name",
},
Birthday: {
mode: "date",
label: "Birthday",
config: {
defaultValueText: "Click here to enter your birthday",
format: (date) => {
return moment(date).format("DD / MM / YYYY");
},
},
},
},
};
class Newform extends Component {
render() {
return (
<KeyboardAvoidingView behavior="padding">
<Text style={styles.setColorGreen} color="#8cba51">
Informations
</Text>
<Form ref="form" type={User} options={options} />
<Button
onPress={() => this.props.navigation.navigate("Chat")}
title="Next"
color="#8cba51"
/>
</KeyboardAvoidingView>
);
}
}
var styles = StyleSheet.create({
setColorGreen: {
color: "#8cba51",
alignItems: "center",
justifyContent: "center",
padding: 20,
fontWeight: "bold",
textAlign: "center",
fontSize: 20,
},
});
export default Newform; ```
You might not pass this component as screen component. Can you please share your Navigator or share your higher level component that has this component in it? The Navigator should look like this:
<Stack.Navigator>
<Stack.Screen name="NewForm" component={NewForm} />
<Stack.Navigator>
Or if you use this component inside a screen component you should pass navigation prop to child component like this
// Stack Navigator
<Stack.Navigator>
<Stack.Screen name="NewForm" component={FormScreen} />
<Stack.Navigator>
class FormScreen extends Component {
render() {
return (
<NewForm {...this.props} />
);
}
}

react native - Passing navigation props from parent to child

I'm trying to create a simple-ish mobile app, but I'm pretty new to this. I've spent some time searching about the errors I'm getting. It seems like a common problem, but they all had the same/similar solutions but the solutions didn't work for me.
What is I'm trying to do? Right now the app is two pages, the home screen (Overview Cards) and the Add Card screen.
There's a button on the Overview Cards that takes you to Add Card.
Add Card allows you to fill out some TextInput boxes and
Add Card should allow you to press the save button and be taken back to the Overview Card screen and see the data you entered in the form.
However, I am getting stuck at Step 3. I am trying to make the Save button navigate the user back to Overview Cards, but there are simply errors instead.
Below is my code, the errors I'm getting, and then what I've tried.
App.js
import React from 'react';
import { StyleSheet, Text, TextInput, View, Button, TouchableOpacity, ShadowPropTypesIOS } from 'react-native';
import AddCard from './components/AddCard.js';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { useNavigation } from '#react-navigation/native';
function HomeScreen({ navigation }) {
return (
<View style={styles.homeContainer}>
<Button title="Add Card" onPress={() => navigation.navigate('Add Card')}/>
{/* <Text value={this.props.inputValFT}/> */}
<Text style={styles.textStyle} >VISA xxxx</Text>
<Text style={styles.textStyle}>MASTERCARD xxxx</Text>
<Text style={styles.textStyle}>AMEX xxxx</Text>
</View>
);
}
function AddCardScreen() {
return (
<View style={styles.addCardContainer}>
<AddCard navigation={this.props.navigation} /> // **HERE**
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} options={{ title: 'Overview Cards' }} />
<Stack.Screen name="Add Card" component={AddCardScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
// function AddCardButton(){
// return (
// <View style={styles.buttonContainer}>
// <TouchableOpacity>
// <Text style={styles.button}>Add Card</Text>
// </TouchableOpacity>
// </View>
// );
// }
export default App;
const styles = StyleSheet.create({
homeContainer: {
flex: 1,
backgroundColor: '#ef95b1',
alignItems: 'center',
justifyContent: 'flex-start',
},
addCardContainer: {
flex: 1,
backgroundColor: '#28cdf0',
justifyContent: 'flex-start',
},
buttonContainer: {
flexDirection: 'row',
alignSelf: 'flex-end',
marginTop: 15,
},
button: {
flexDirection: 'row',
alignSelf: 'flex-end',
marginTop: 15,
right: 10,
backgroundColor: '#2565ae',
borderWidth: 1,
borderRadius: 12,
color: 'white',
fontSize: 15,
fontWeight: 'bold',
overflow: 'hidden',
padding: 10,
textAlign:'center',
},
textStyle: {
padding: 10,
}
});
Navigation.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import AddCardScreen from './AddCard';
const RootStack = createStackNavigator(
{
Home: HomeScreen,
AddCard: AddCardScreen,
},
{
initialRouteName: 'Home',
}
);
const AppContainer = createAppContainer(RootStack);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ef95b1',
alignItems: 'center',
justifyContent: 'flex-start',
},
textStyle: {
padding: 10,
}
});
export default createAppContainer(Navigation);
AddCard.js
import React, { Component } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity } from 'react-native';
import { Input } from 'react-native-elements'
import { ScrollView } from 'react-native-gesture-handler';
// import { loadSettings, saveSettings } from '../storage/settingsStorage';
class AddCardScreen extends Component {
constructor(props) {
super(props);
this.state = {
firstTwo : '',
lastFour : '',
recentAmt : ''
};
this.addFT = this.addFT.bind(this)
this.addLF = this.addLF.bind(this)
this.addRecAmt = this.addRecAmt.bind(this)
}
static navigationOptions = {
title: 'Add Card'
};
addFT(firstTwo) {
this.setState(Object.assign({}, this.state.firstTwo, { firstTwo }));
}
addLF(lastFour) {
this.setState(Object.assign({}, this.state.lastFour, { lastFour }));
}
addRecAmt(recentAmt) {
this.setState(Object.assign({}, this.state.recentAmt, { recentAmt }));
}
// handleSubmit() {
// alert('New card saved. Returning to Home to view addition.');
// navigation.navigate('Home')
// } // firstTwo, lastFour, recentAmt
render() {
const {navigation} = this.props;
return (
<ScrollView>
<View style={styles.inputContainer}>
<Text h1> "Add a new card!" </Text>
<TextInput
style={styles.textInput}
placeholder="First two digits of card"
placeholderTextColor="#000000"
keyboardType={'number-pad'}
maxLength = {2}
onChangeText={this.addFT}
inputValFT={this.state.firstTwo}
/>
<TextInput
style={styles.textInput}
placeholder="Last four digits of card"
placeholderTextColor="#000000"
keyboardType={'number-pad'}
maxLength = {4}
onChangeText={this.addLF}
inputValLF={this.state.lastFour}
/>
<TextInput
style={styles.textInput}
placeholder="Most recent dollar amount"
placeholderTextColor="#000000"
keyboardType={'decimal-pad'}
onChangeText={this.addRecAmt}
inputValRA={this.state.recentAmt}
/>
</View>
<View style={styles.inputContainer}>
<TouchableOpacity
style={styles.saveButton}
onPress={() => navigation.navigate('Home')}> // ** HERE 2 **
<Text style={styles.saveButtonText}>Save</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
// this.handleSubmit.bind(this)
export default AddCardScreen;
const styles = StyleSheet.create({
inputContainer: {
paddingTop: 15
},
textInput: {
borderColor: '#FFFFFF',
textAlign: 'center',
borderTopWidth: 1,
borderBottomWidth: 1,
height: 50,
fontSize: 17,
paddingLeft: 20,
paddingRight: 20
},
saveButton: {
borderWidth: 1,
borderColor: '#007BFF',
backgroundColor: '#007BFF',
padding: 15,
margin: 5
},
saveButtonText: {
color: '#FFFFFF',
fontSize: 20,
textAlign: 'center'
}
});
The errors I'm getting:
In App.js you can see the ** HERE ** that I put in. When I try to run this, the app loads fine until I click the "Add Card" button. I get this error: undefined is not an object (evaluating 'this.props.navigation').
If I take the navigate={this.props.navigation} part out from App.js, the app loads as it's meant to again, but this time I can click the "Add Card" button and reach the next screen with no issue. I fill out the form (TextInput parts in AddCard.js), but when I click the "Save" button, the app crashes. The error is: TypeError: undefined is not an object (evaluating 'navigation.navigate'). Most likely because of what I'm doing with onPress where it says ** HERE 2 ** in AddCard.js. handleSubmit() is currently commented out, but it used to be inside the onPress.
What I've tried:
Some of the answers I saw were that I need to pass in navigation from the parent to the child and that will make it work. By trying that, I get the errors I mentioned earlier. I also saw that someone mentioned using "withNavigation" or "useNavigation" which was supposed to allow the child to access navigation, but that didn't work for me either. Below are some of the links that I was trying to follow.
How do I pass navigation props from parent component to header?
Pass navigation.navigate to Child Component
https://reactnavigation.org/docs/use-navigation/
Thank you for reading, hopefully my explanation is clear enough.
I think your problem is somewhere here:
function AddCardScreen({ navigation }) {
return (
<View style={styles.addCardContainer}>
<AddCard navigation={navigation} />
</View>
);
}
There is no this, you're not in a class component, therefore this doesn't exists
The prop you are trying to pass should be called navigation and not navigate, since that's how you try to access it in the child component.
The navigation prop needs to be destructured inside the function argument function AddCardScreen({ navigation }), same as you already do for HomeScreen.

How To navigate from createMaterialTopTabNavigatorto other screen - React Navigation?

I have some issue when navigating from top Tabnavigator to other screens
so my app navigation is
My Orders Screen from Drawer => Top TabNavigatore (Accepted/Completed) => Order Details
In Route.js
I put every single navigation I want like Drawer - Auth navigation and so on, and I put a StackNavigator contain the Orders Screen like this:
const OrdersStack = createStackNavigator({
Orders: {
screen: Orders,
navigationOptions: ({ navigation }) => ({
headerLeft: (
// <TouchableOpacity onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())}>
<TouchableOpacity
onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())}
>
<Icon
name="ios-menu"
size={40}
style={{ margin: 10 }}
color="#2F98AE"
/>
</TouchableOpacity>
),
headerRight: <View />,
title: "My Orders",
headerTintColor: "#2F98AE",
headerStyle: {
borderBottomColor: "white"
},
headerTitleStyle: {
color: "#2F98AE",
// textAlign: "center",
flex: 1,
elevation: 0,
fontSize: 25
// justifyContent: "center"
}
})
}
});
In the Orders.js I put these:
import React, { Component } from "react";
import { createAppContainer, createStackNavigator } from "react-navigation";
import NavTabs from "../screens/NavTabs";
import NavOrderDetails from "../screens/NavOrderDetails";
// create a component
export default class Orders extends Component {
render() {
return <MyOrdersScreen />;
}
}
export const root = createStackNavigator({
NavTabs: NavTabs,
NavOrderDetails: NavOrderDetails
});
const MyOrdersScreen = createAppContainer(root);
As I mentioned in Orders.js it Contains Tabs and Order Details
In Tabs, I'm creating a createMaterialTopTabNavigator
import { createMaterialTopTabNavigator } from "react-navigation";
import AcceptedOrders from "../screens/AcceptedOrders";
import CompletedOrders from "../screens/CompletedOrders";
const MainTabs = createMaterialTopTabNavigator(
{
Accepted: { screen: AcceptedOrders },
Completed: { screen: CompletedOrders }
},
{
tabBarOptions: {
activeTintColor: "#fff",
inactiveTintColor: "#ddd",
tabStyle: {
justifyContent: "center"
},
indicatorStyle: {
backgroundColor: "#fcc11e"
},
style: {
backgroundColor: "#2F98AE"
}
}
}
);
export default MainTabs;
and another screen is OrderDeatils.js
import { createStackNavigator } from "react-navigation";
import OrderDetails from "../screens/OrderDetails";
import React, { Component } from "react";
import { View } from "react-native";
const OrderDetailsStack = createStackNavigator({
OrderDetails: {
screen: OrderDetails,
navigationOptions: () => ({
title: "Order Details",
headerRight: <View />,
headerTintColor: "#2F98AE",
headerStyle: {
borderBottomColor: "white"
},
headerTitleStyle: {
color: "#2F98AE",
flex: 1,
elevation: 0,
fontSize: 25
}
})
}
});
export default OrderDetailsStack;
Here are a screenShots it should explain what I mean
1- My Orders
2- Order Details
If i understand, you are concerned about the blank header that appears on top of the screen under your first header.
That one is created by createStackNavigator.
A the first Stack that creates the first Header named OrdersStack.
Inside that you have the root constant (probably, as there isn't the full code) that is creating the second header.
Inside root you are then defining your createMaterialTopTabNavigator with your two screens, that's showing the topBar with the label "accepted" and "completed".
To hide that white space you have to disable your root header doing:
export const root = createStackNavigator({
NavTabs: NavTabs,
NavOrderDetails: NavOrderDetails
},
{
defaultNavigationOptions:{
header:null
}
});
UPDATE.
You have two ways to fix this and still have a backButton:
1) You can either create a parent CustomHeader that, using react-navigation's withNavigation HOC, is aware about his childrens navigation state.
2) Dinamically hide the parent header when the second one is showing. You can accomplish this using this.props.navigation.dangerouslyGetParent().dangerouslyGetParent().setParams({showHeader:false})
then your OrdersStack would be:
const OrdersStack = createStackNavigator({
Orders: {
screen: Orders,
navigationOptions: ({ navigation }) => {
var defaultHeader={
headerLeft: (
<TouchableOpacity
onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())}
>
<Icon
name="ios-menu"
size={40}
style={{ margin: 10 }}
color="#2F98AE"
/>
</TouchableOpacity>
),
headerRight: <View />,
title: "My Orders",
headerTintColor: "#2F98AE",
headerStyle: {
borderBottomColor: "white"
},
headerTitleStyle: {
color: "#2F98AE",
// textAlign: "center",
flex: 1,
elevation: 0,
fontSize: 25
// justifyContent: "center"
}
}
if (navigation.state.params)
return(navigation.state.params.showHeader?{defaultHeader}:null)
else return defaultHeader
}
}
});

React Native, change React Navigation header styling

I'm implementing React Navigation in my React Native app, and I'm wanting to change the background and foreground colors of the header. I have the following:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
export default class ReactNativePlayground extends Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
const SimpleApp = StackNavigator({
Home: { screen: ReactNativePlayground }
});
AppRegistry.registerComponent('ReactNativePlayground', () => SimpleApp);
By default the background color of the heading is white, with a black foreground. I've also looked at the documentation for React Navigation but I'm not able to find where it shows how to set the styling. Any help?
In newer versions of React Navigation you have a flatter settings object, like below:
static navigationOptions = {
title: 'Chat',
headerStyle: { backgroundColor: 'red' },
headerTitleStyle: { color: 'green' },
}
Deprecated answer:
Per the docs, here, you modify the navigationOptions object. Try something like:
static navigationOptions = {
title: 'Welcome',
header: {
style: {{ backgroundColor: 'red' }},
titleStyle: {{ color: 'green' }},
}
}
Please don't actually end up using those colors though!
According to documentation you can use "navigationOptions" style like this.
static navigationOptions = {
title: 'Chat',
headerStyle:{ backgroundColor: '#FFF'},
headerTitleStyle:{ color: 'green'},
}
For more info about navigationOptions you can also read from docs:-
https://reactnavigation.org/docs/navigators/stack#Screen-Navigation-Options
Try this working code
static navigationOptions = {
title: 'Home',
headerTintColor: '#ffffff',
headerStyle: {
backgroundColor: '#2F95D6',
borderBottomColor: '#ffffff',
borderBottomWidth: 3,
},
headerTitleStyle: {
fontSize: 18,
},
};
Notice! navigationOptions is differences between Stack Navigation and Drawer Navigation
Stack Navigation Solved.
But for Drawer Navigation you Can add Your own Header and Make Your Styles with contentComponent Config:
First import { DrawerItems, DrawerNavigation } from 'react-navigation' Then
Header Before DrawerItems:
contentComponent: props => <ScrollView><Text>Your Own Header Area Before</Text><DrawerItems {...props} /></ScrollView> .
Footer After DrawerItems:
contentComponent: props => <ScrollView><DrawerItems {...props} /><Text>Your Own Footer Area After</Text></ScrollView> .
Try this code:
static navigationOptions = {
headerTitle: 'SignIn',
headerTintColor: '#F44336'
};
good luck!

Categories