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!
Related
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
I have main Tabs "Categories" and I want when I click to any one of them it will just appeared his Details,
so I'm decleare a flag to every category and update it when clicked to display category details, BUT I think this is a wrong idea! and other issue when I click to first category it's appear his details, but when I clicked other Category from the tabs, the first category it's still around!
So how can I handle these issue?
Snack Here
Here's my Code
import React, { Component } from 'react';
import { Text, View, ScrollView,TouchableOpacity } from 'react-native';
export default class App extends Component {
state = {
open:true,
cat2:false,
cat3:false,
cat4:false,
}
render() {
return (
<View style={{flex: 1}} >
<ScrollView style={{flexGrow: 0.05, backgroundColor: '#347ed8', paddingTop: 50}} horizontal>
<TouchableOpacity onPress={()=>this.setState({open:!this.state.open})} style={{width: 100}}><Text style={{color:"#fff",fontSize:18}}>cat1 </Text></TouchableOpacity>
<TouchableOpacity
onPress={()=>this.setState({
cat2:!this.state.cat2
})}
style={{width: 100}}><Text style={{color:"#fff",fontSize:18}}>Cat2</Text></TouchableOpacity>
<TouchableOpacity style={{width: 100}}><Text style={{color:"#fff",fontSize:18}}>Cat3</Text></TouchableOpacity>
<TouchableOpacity style={{width: 100}}><Text style={{color:"#fff",fontSize:18}}>Cat4</Text></TouchableOpacity>
<TouchableOpacity style={{width: 100}}><Text style={{color:"#fff",fontSize:18}}>Cat5</Text></TouchableOpacity>
</ScrollView>
<View style={{flex: 0.95, backgroundColor: '#ddd'}}>
{this.state.open && <View>
<Text>Category Details One Here</Text>
</View>}
{this.state.cat2 && <View>
<Text>Category Details Two Here!</Text>
</View>}
{this.state.cat3 && <View>
<Text>Category Details Three Here!</Text>
</View>}
{this.state.cat4 && <View>
<Text>Category Details four Here!</Text>
</View>}
</View>
</View>
);
}
}
A simple solution to do what you want is to use a React-navigation module.
This problem should be that you have not set up touch events elsewhere, and the values shown by setting the conditions for touch events are different. However, this condition can mess up your code, which can be handled simply using the 'React-navigation' module.
You can use createMaterialTopTabNavigator
Example
import {
createStackNavigator,
createMaterialTopTabNavigator,//React navigation version 4 and before
createAppContainer,
} from 'react-navigation';
import { createMaterialTopTabNavigator } from 'react-navigation-tabs'; //React navigation version 4
//import Navigator in our project
import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
//Making TabNavigator which will be called in App StackNavigator
//we can directly export the TabNavigator also but header will not be visible
//as header comes only when we put anything into StackNavigator and then export
const TabScreen = createMaterialTopTabNavigator(
{
Home: { screen: FirstPage },
Settings: { screen: SecondPage },
},
{
tabBarPosition: 'top',
swipeEnabled: true,
animationEnabled: true,
tabBarOptions: {
activeTintColor: '#FFFFFF',
inactiveTintColor: '#F8F8F8',
style: {
backgroundColor: '#633689',
},
labelStyle: {
textAlign: 'center',
},
indicatorStyle: {
borderBottomColor: '#87B56A',
borderBottomWidth: 2,
},
},
}
);
//making a StackNavigator to export as default
const App = createStackNavigator({
TabScreen: {
screen: TabScreen,
navigationOptions: {
headerStyle: {
backgroundColor: '#633689',
},
headerTintColor: '#FFFFFF',
title: 'TabExample',
},
},
});
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
}
}
});
I'm new to react native, but I've been researching how to redirect to new activities with buttons for the last few hours with no avail. My current solution involves me using react-navigation from multiple files, with App.js creating the StackNavigator for the rest of the pages. However, whenever I press the button on Initial.js, nothing happens.
I followed Damien Manson's tutorial on Invariant Violation: The navigation prop is missing for this navigator, but the button still doesn't work. I tried referencing App before calling my button, but whenever I try to run it on the emulator, it doesn't show me an error log and it never loads. It stays at "Downloading JavaScript bundle: 100%" for minutes until the emulator itself crashes.
Here's my App.js
import Initial from './components/Initial'
import Statistics from './components/Statistics'
const RootStack = createStackNavigator({
Default: {
screen: Initial
},
Stats: {
screen: Statistics
}
});
const App = createAppContainer(RootStack);
export default App;
Here's my Initial.js
import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';
import App from '../App';
import {withNavigation} from 'react-navigation';
import Statistics from './Statistics';
export default class Initial extends React.Component {
static navigationOptions = {header: null}
componentDidMount() {
Font.loadAsync({'pt': require('../assets/fonts/pt.ttf')});
Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf')});
Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf')});
}
state = { fontLoaded: false};
async componentDidMount() {
await Font.loadAsync({'pt': require('../assets/fonts/pt.ttf'),});
await Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf'),});
await Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf'),});
this.setState({fontLoaded: true});
}
render() {
return (
<ImageBackground
source = {require('../assets/blue-bin.jpg')}
style = {styles.container}>
<View style = {styles.parentView}>
{this.state.fontLoaded ? (<Text style={styles.logoText}>!arbitrary</Text>) : null}
<Image source = {require('../assets/sadparrot.gif')} style = {styles.logo}/>
<Text style = {styles.textBox}>With its easily navigatible interface, the Chicago-based app, !arbitrary, aims to educate the masses about recyclable items, while emphasizing the importance of being sustainable.</Text>
<View style = {styles.redirect}>
<Button
title="Start"
onPress={() => this.props.navigation.navigate('Statistics')}
/>
</View>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
height: '100%',
},
parentView: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'rgba(5,9,12, 0.6)',
justifyContent: 'center',
alignItems: 'center'
},
logoText: {
color: '#fff',
fontSize: 36,
fontFamily: 'pt'
},
textBox: {
width: 200,
height: 175,
fontFamily: 'sans-serif',
fontSize: 14,
color: '#fff',
borderColor: '#fff',
borderWidth: 2,
justifyContent: 'center',
marginTop: 50,
padding: 20
},
logo: {
width: 200,
height: 200
},
redirect: {
width: 80,
height: 30,
marginTop: 30
},
statistics: {
flex: 1,
width: '100%',
height: '100%',
backgroundColor: '#1B384F'
},
bigText: {
color: '#fff',
fontSize: 20,
fontFamily: 'Space-Mono'
}
});
Here's my Statistics.js
import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';
import {withNavigation} from 'react-navigation';
class Statistics extends React.Component {
render() {
return(
<Text>Avail!</Text>
);
}
}
export default withNavigation(Statistics);
NOTE: I omitted my StyleSheet in Initial.js for the sake of being concise.
You need to navigate to your screen name which is Stats.
<Button
title="Start"
onPress={() => this.props.navigation.navigate('Stats')}/>
I had the same issue. I fixed is by using withNavigation
In Statistics class,
1st, Import withNavigation.
import { withNavigation } from 'react-navigation';
Then, export Statistics class as below.
export default withNavigation(Statistics)
Try this
const RootStack = createStackNavigator({
Default: {
screen: Initial
},
Stats: {
screen: props => <Statistics {...props} />
}
});
I'm trying to create a React Native app with some basic routing.
This is my code so far:
App.js:
import React from 'react'
import { StackNavigator } from 'react-navigation'
import MainScreen from './classes/MainScreen'
const AppNavigator = StackNavigator(
{
Index: {
screen: MainScreen,
},
},
{
initialRouteName: 'Index',
headerMode: 'none'
}
);
export default () => <AppNavigator />
MainScreen.js:
import React, { Component } from 'react'
import { StyleSheet, Text, View, Button, TouchableOpacity, Image } from 'react-native'
import HomeButton from './HomeButton'
export default class MainScreen extends Component {
static navigatorOptions = {
title: 'MyApp'
}
constructor(props) {
super(props)
}
render() {
return (
<View style={styles.container}>
<Image source={require('../img/logo.png')} style={{marginBottom: 20}} />
<HomeButton text='Try me out' classType='first' />
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
HomeButton.js:
import React, { Component } from 'react'
import { StyleSheet, Text, View, Button, TouchableOpacity } from 'react-native'
import { StackNavigator } from 'react-navigation'
export default class HomeButton extends Component {
constructor(props) {
super(props)
}
render() {
return (
<TouchableOpacity
onPress={() => navigate('Home')}
style={[baseStyle.buttons, styles[this.props.classType].style]}
>
<Text style={baseStyle.buttonsText}>{this.props.text.toUpperCase()}</Text>
</TouchableOpacity>
)
}
}
var Dimensions = require('Dimensions')
var windowWidth = Dimensions.get('window').width;
const baseStyle = StyleSheet.create({
buttons: {
backgroundColor: '#ccc',
borderRadius: 2,
width: windowWidth * 0.8,
height: 50,
shadowOffset: {width: 0, height: 2 },
shadowOpacity: 0.26,
shadowRadius: 5,
shadowColor: '#000000',
marginTop: 5,
marginBottom: 5
},
buttonsText: {
fontSize: 20,
lineHeight: 50,
textAlign: 'center',
color: '#fff'
}
})
const styles = {
first: StyleSheet.create({
style: { backgroundColor: '#4caf50' }
})
}
Everything works fine, but when pressing the button I get
Can't find variable: navigate
I've read that I have to declare it like this:
const { navigate } = this.props.navigation
So I edited HomeButton.js and added that line at the beginning of the render function:
render() {
const { navigate } = this.props.navigation
return (
<TouchableOpacity
onPress={() => navigate('Home')}
style={[baseStyle.buttons, styles[this.props.classType].style]}
>
<Text style={baseStyle.buttonsText}>{this.props.text.toUpperCase()}</Text>
</TouchableOpacity>
)
}
Now I get:
TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate')
It seems that the navigation object is not coming into the properties, but I don't understand where should I get it from.
What am I missing here?
React-navigation pass navigation prop to the screen components defined in the stack navigator.
So in your case, MainScreen can access this.props.navigation but HomeButton can't.
It should work if you pass navigation prop from MainScreen to HomeButton :
<HomeButton text='Try me out' classType='first' navigation={this.props.navigation}/>
Edit: You have to define the Homescreen in your stack navigator in order to navigate to it, your onPress={() => navigate('Home')} won't work until then.