I'm trying react navigation inside my react native project. I using TabNavigator for content switching and I would like to make a fixed top bar with my logo inside, each time i swipe to change the tab content, the logo are stick on the top and not moving.
Now i just put the topcontainer inside my HomeScreen
class HomeScreen extends React.Component {
render() {
return(
<View style={styles.container}>
<View style={styles.topcontainer}>
<View style={styles.applogocontainer}>
<Image
source={require('./resources/logo.png')}
style={styles.applogo}
/>
</View>
</View>
</View>
);
}
}
class SecondScreen extends React.Component {
render() {
return(
<View style={styles.container}>
<Text style={styles.whitetext}>Second</Text>
</View>
);
}
}
class ThirdScreen extends React.Component {
render() {
return(
<View style={styles.container}>
<Text style={styles.whitetext}>Third</Text>
</View>
);
}
}
const TabNavs = TabNavigator({
Home: { screen: HomeScreen },
Second: { screen: SecondScreen },
Third: { screen: ThirdScreen },
},{
tabBarPosition:'bottom',
swipeEnabled:true,
tabBarOptions:{
tinColor: '#fff',
activeTintColor: '#eee',
inactiveTintColor: '#fff',
style: {
position: 'absolute',
backgroundColor: 'transparent',
left: 0,
right: 0,
bottom: 0,
},
indicatorStyle:{
backgroundColor:'white'
},
showIcon:true
}
}
);
Yes for topBar menu you can use navigationOptions, is best practise for it:
class MainScreen extends React.Component {
static navigationOptions = () => ({
header: (<YourComponentCustom />),
// others options see you : https://reactnavigation.org/docs/en/headers.html
});
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
// your code
);
}
}
export default MainScreen;
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
}
class SecondScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
}
}
const RootStack = StackNavigator(
{
Home: {
screen: HomeScreen,
},
SecondScreen: {
screen: SecondScreen,
},
},
{
initialRouteName: 'Home',
navigationOptions: {
header: (
<View style={styles.container}>
<View style={styles.topcontainer}>
<View style={styles.applogocontainer}>
<Image
source={require('./resources/logo.png')}
style={styles.applogo}
/>
</View>
</View>
</View>
)
},
}
);
You can use custom header. See detail from this
Related
I would like to create a simple navigation example on ReactNative.
Here is a code below;
import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';
import { createStackNavigator } from 'react-navigation-stack';
class Home extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home</Text>
<Button
title="To the detail Page"
onPress={() => this.props.navigation.navigate('DetailScreen')}
/>
</View>
);
}
}
class Detail extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Detail Page</Text>
</View>
);
}
}
export default createStackNavigator({
HomeScreen: { screen: Home },
DetailScreen: { screen: Detail },
})
When I code like this, an error is occurred as Line12 this.props.navigation is undefined.
Does anyone have a solution?
Please try the below code :
import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';
import {
createAppContainer
} from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
class Home extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home</Text>
<Button
title="To the detail Page"
onPress={() => this.props.navigation.navigate('DetailScreen')}
/>
</View>
);
}
}
class Detail extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Detail Page</Text>
</View>
);
}
}
const APpStack = createStackNavigator({
HomeScreen: { screen: Home },
DetailScreen: { screen: Detail },
})
const App = createAppContainer(APpStack);
export default App;
You can also check the working solution link expo
hope it helps. feel free for doubts
You need a constructor to define properties that are used for storing navigation data (among others):
class Home extends React.Component {
constructor(props) {
super(props);
// ...
}
I am using react-native-overlay-section. The bottom sheet is swipeable to the whole window but I want it to be swipeable to a particular height. How should I do? I have uploaded the code below:
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet
} from 'react-native';
import SlideUp from 'react-native-overlay-section';
export default class App extends Component {
constructor (props) {
super(props);
}
exampleContent = () => {
return (
<View >
<Text>This is test text</Text>
</View>
)
}
render() {
return (
<View style={{flex: 1}}>
<Text>Hello</Text>
<SlideUp
contentSection={this.exampleContent()}
draggableHeight={50}
/>
</View>
)
}
}
Here is the style:
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
I have a stack navigator structure like this
index.js -> App.js -> LoginStck, HomeNavStack
From LoginStck on successful login I go to HomeNavStack
and from while doing this I reset the stack to have only HomeNavStack(did that to avoid login screen when going back) In HomeStack there are 4 tabs namely Home/Payment/Profile/More with separate stack for each tab. I navigate to MoreScreen within More tab and won logout I need to go to Login Stack(the very first one discarding all other screen).
I did try this`
dothis = async () => {
const someAction = StackActions.reset({
index: 0,
key: null,
actions: [
NavigationActions.navigate({ routeName: 'HomeNavigatorNew'})
]
});
this.props.navigation.navigate(someAction)
}
but didn't work. Any insights....??
Thanks in Advance
`
The recommend way to switch between Login and other screens is by using createSwitchNavigator.
For more information please check:
https://reactnavigation.org/docs/en/switch-navigator.html#docsNav
I created a simple example that can be helpful for your case:
import React from 'react';
import {
View,
Text,
Button,
} from 'react-native';
import {
createStackNavigator,
createBottomTabNavigator,
createSwitchNavigator,
} from 'react-navigation';
class LoginScreen extends React.Component {
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>LoginScreen</Text>
<Button
title={'Login'}
onPress={() => this.props.navigation.navigate('HomeStack')}
/>
</View>
)
}
}
class PaymentScreen extends React.Component {
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>PaymentScreen</Text>
</View>
)
}
}
class ProfileScreen extends React.Component {
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>ProfileScreen</Text>
</View>
)
}
}
class MoreScreen extends React.Component {
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>MoreScreen</Text>
<Button
title={'Logout'}
onPress={() => this.props.navigation.navigate('LoginStack')}
/>
</View>
)
}
}
const PaymentStack = createStackNavigator(
{
Payment: PaymentScreen,
}
);
const ProfileStack = createStackNavigator(
{
Profile: ProfileScreen,
}
);
const MoreStack = createStackNavigator(
{
More: MoreScreen,
}
);
const HomeStack = createBottomTabNavigator(
{
PaymentStack: PaymentStack,
ProfileStack: ProfileStack,
MoreStack: MoreStack,
}
);
const LoginStack = createStackNavigator(
{
Login: LoginScreen,
}
);
export default createSwitchNavigator(
{
LoginStack: LoginStack,
HomeStack: HomeStack,
}
);
I have created custom tabs in react-native but I am unable to select a tab. I have initialized the state for the selected tab but do not know where to set the state.
here is my code:
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Image,
View
} from 'react-native';
var Dimensions = require('Dimensions');
var windowSize = Dimensions.get('window');
var bg = require('image!bg');
class TabView extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'list',
selectedTab: 'map'
};
}
render() {
return (
<View style={styles.container}>
<Image style={styles.bg} source={bg} />
<View style={styles.tabView}>
<View style={[styles.listView,styles.selectedView]}>
<Text>List View</Text>
</View>
<View style={[styles.listView,{}]}>
<Text>Map View</Text>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
bg: {
position: 'absolute',
left: 0,
top: 0,
width: windowSize.width,
height: windowSize.height
},
tabView: {
flexDirection: 'row',
//bottom: 200,
borderWidth:2,
borderColor:'rgba(4, 193, 3,1)',
borderRadius: 5,
marginHorizontal: 20,
marginTop: 50
},
listView: {
flex: 2,
padding:7,
alignItems:'center'
},
mapView: {
flex: 2,
padding:7,
alignItems:'center'
},
selectedView: {
backgroundColor:'rgba(4, 193, 3,1)',
color: 'white'
}
});
module.exports = TabView
I just want to know where shall I add a check so that I can make a difference in the selected tab
Any help will be appreciated.
Please, check out the code here, to get an idea how it can be done
const Tab = (props) => {
let style = props.isSelected && styles.selectedTab || styles.normalTab;
return (
<View style={style}>
<TouchableHighlight onPress={() => props.onTabPress(props.id)}>
<Text>{props.title}</Text>
</TouchableHighlight>
</View>
)
}
class TabsView extends Component {
constructor(props) {
super(props)
this.state = {
selectedTab: 'one'
}
}
render() {
return (
<View>
<Tab onTabPress={this.onSelectTab.bind(this)} title="One" id="one" isSelected={this.state.selectedTab == "one"}/>
<Tab onTabPress={this.onSelectTab.bind(this)} title="Two" id="two" isSelected={this.state.selectedTab == "two"}/>
</View>
)
}
onSelectTab(selectedTab) {
this.setState({ selectedTab })
}
}
The above code splits your component in two parts, a logical part (TabsView) and a dumb presentational part (Tab)
The logical handles the clickHandler (onSelectTab) which is passed as a prop (onTabPress) to the dumb (Tab) Component.
I just want to know where shall I add a check so that I can make a difference in the selected tab
In the render method, it should go
example:
render() {
let FirstTabStyles = Object.assign(
defaultTabStyles,
(isFirstSelected && selectedStyles || {})
)
let SecondTabStyle = Object.assign(
defaultTabStyles,
(isSecondSelected && selectedStyles || {})
)
return (
<View>
<FirstTab style={FirstTabStyle} />
<SecondTab style={SecondTabStyle} />
</View>
)
}
I am new to React Native I am making a sample app where the user can login and register for a new account.
I have two React classes,
One is the main class index.ios.js and another class called register.js. In the index class I am saying if the variable register is true render the register screen.
In the class register.js I am trying to set the variable register to false using this.setState({register:false}) but it is not causing the re render of the parent (index.ios.js). Is the a super(state) method or something similar that I am missing ? I believe the parent state is not getting the values of the updated register variable.
Here are my classes:
Render inside index.ios.js:
render: function() {
if(this.state.register) {
return this.renderRegisterScreen();
}
else if (this.state.loggedIn) {
return this.userLoggedIn();
}
else {
return this.renderLoginScreen();
}
}
Register.js:
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableHighlight,
TextInput,
} = React;
var Register = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.rafitoImage}>
<Image source={require('./logo.png')}></Image>
<Text style={styles.slogan}>Eliminate the need to wait!</Text>
</View>
<View style={styles.bottomSection}>
<View style={styles.username}>
<View style={styles.inputBorder}>
<TextInput placeholder="Username..." style={styles.usernameInput} onChangeText={(text) => this.setState({username: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput password={true} placeholder="Password..." style={styles.usernameInput} onChangeText={(text) => this.setState({password: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput password={true} placeholder="Verify Password..." style={styles.usernameInput} onChangeText={(text) => this.setState({verifyPassword: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput placeholder="Phone.." style={styles.usernameInput} onChangeText={(text) => this.setState({phone: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput placeholder="Email.." style={styles.usernameInput} onChangeText={(text) => this.setState({email: text})}/>
</View>
<TouchableHighlight style={styles.button}
underlayColor='#f1c40f' onPress={this.register}>
<Text style={styles.buttonText}>Register</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.signUp} onPress={this.resetToLogin}
underlayColor='#ffffff'>
<Text style={styles.signUpText}>Already A Member </Text>
</TouchableHighlight>
</View>
</View>
<View style={styles.copyright}>
</View>
</View>
);
},
resetToLogin: function() {
this.setState({
register: false //I want this to re render the home screen with the variable register as false
});
}
});
var styles = StyleSheet.create({
container: {
flex : 1
},
bottomSection: {
flex: 5,
flexDirection: 'row'
},
button: {
height: 36,
backgroundColor: '#32c5d2',
justifyContent: 'center',
marginTop: 20
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
signUpText: {
color: '#3598dc'
},
signUp: {
alignItems: 'flex-end',
marginTop: 10,
},
username: {
flex: 1,
padding: 5
},
rafitoImage: {
flex: 3,
justifyContent: 'center',
alignItems: 'center',
},
copyright: {
alignItems: 'center'
},
usernameInput: {
height: 36,
marginTop: 10,
marginBottom: 10,
fontSize: 18,
padding: 5
},
copyrightText: {
color: '#cccccc',
fontSize: 12
},
inputBorder: {
borderBottomWidth: 1,
borderBottomColor: '#ececec'
},
slogan: {
color: '#3598dc'
}
});
module.exports = Register;
Attempt 1
As per the answer I added this to my index.ios.js
renderRegisterScreen: function() {
return (
<Register login={this.login}/>
)
}
And I added this to my register.js
<TouchableHighlight style={styles.signUp} onPress={this.props.login}
underlayColor='#ffffff'>
<Text style={styles.signUpText}>Already A Member </Text>
</TouchableHighlight>
But for some reason it does not even go to the register screen anymore, it executes the login function as soon as the register screen renders. What am I missing now ? Please advise.
Thanks
Update
It works when I pass down registered as a property but not when I do not. I would like to understand why if someone could post that.
Thanks
You can pass the function down to the child as props, then set the state of the parent from within the child that way.
Parent Component:
var Parent = React.createClass({
getInitialState() {
return {
registered: false
}
},
register(){
console.log("logging in... ");
this.setState({
registered: true
});
},
render: function() {
return (
<View style={styles.container}>
<Child register={this.register.bind(this)} registered={this.state.registered} />
{this.state.registered && <View style={{padding:10, backgroundColor:'white', marginTop:10}}>
<Text style={{fontSize:20}}>Congratulations, you are now registered!</Text>
</View>}
</View>
);
}
});
Child Component:
var Child = React.createClass({
render: function() {
return(
<View style={{backgroundColor: 'red', paddingBottom:20, paddingTop:20 }}>
<TouchableHighlight style={{padding:20, color: 'white', backgroundColor: 'black'}} onPress={() => this.props.register() }>
{this.props.registered ? <Text style={{color: 'white'}}>registered</Text> : <Text style={{color: 'white'}}>register</Text>}
</TouchableHighlight>
</View>
)
}
})
Here is a more powerful solution. This will let the child component change any state variable in the parent.
Parent component:
render: function() {
return (
...
<Child setParentState={newState=>this.setState(newState)} />
...
);
}
// Take note of the setState()
Child component:
this.props.setParentState({registered: true})
Why my attempt was failing was because I was using
onPress={this.props.login}
It should be
onPress={()=>this.props.login}
because of that mistake my onPress function would execute as soon as the button would render. I am not sure why that happens but I know what my mistake was.
Using StackNavigator I found a soultion leveraging screenProps. Here you can pass down functions and values to your routes. App global state is managed in App. App then passes in functions and/or state to NavComponent screenProps. Each child route in StackNavigator will then have access via this.props.screenProps
This solution is working well for now. Would love some feedback, or suggestions for improving this method
class HomeScreen extends React.Component {
render() {
return (
<View>
<Text>{JSON.stringify(this.props.screenProps.awesome)}</Text>
<Button
onPress={() => this.props.screenProps.updateGlobalState("data")}
title="Update parent State"
/>
</View>
);
}
}
const NavComponent = StackNavigator({
Home: { screen: HomeScreen },
// AllOthers: { screen: AllComponentsHereMayAccessScreenProps },
});
export default class App extends React.Component {
constructor() {
super();
this.state = {
everythingIsAwesome: false,
}
}
_updateGlobalState(payload) {
console.log('updating global state: ', payload);
this.setState({everythingIsAwesome: payload});
}
render() {
return <NavComponent screenProps={{
updateGlobalState: this._updateGlobalState.bind(this),
awesome: this.state.everythingIsAwesome
}} />;
}
}