I have a problem.
I want after I successfully add product to cart my shopping cart badge will be updated. But I can't setState the itemCart component.
This is code when i add products in cart.
Function _datmon() will do that.
import React, { Component } from 'react';
import {View,Text,StyleSheet,Dimensions,Image, TouchableOpacity,Modal, Button, Alert} from 'react-native';
import { RecyclerListView, DataProvider, LayoutProvider } from "recyclerlistview";
import { Snackbar} from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import AsyncStorage from '#react-native-community/async-storage';
import Home from '../Home';
import 'regenerator-runtime/runtime';
export default class FoodByList extends Component{
constructor(props){
super(props);
this.state={
mang:[],
dataProvider: new DataProvider ((r1,r2)=> r1!==r2),
statusInform:false,
modalVisible: false,
id:'',
gia:'',
mota:'',
soluong:1,
mangmonan:[{
id:'',
soluong:'',
}],
getArr:[],
hide: true,
}
this.home = new Home();
this.homeref = React.createRef();
}
openModalWithItem(item) {
this.setState({
ten: item.ten,
gia: item.gia,
hinhanh: item.hinhanh,
id: item.id,
mota: item.mota,
})
}
layoutProvider = new LayoutProvider(
index => {
return index;
},
(type,dim) => {
dim.width = Dimensions.get('window').width/2;
dim.height = 280;
}
)
_datmon = async()=>{
//Get array availible device
try {
const myArray = await AsyncStorage.getItem('keyOrdermonan');
if (myArray !== null) {
// We have data!!
console.log(JSON.parse(myArray));
}
} catch (error) {
// Error retrieving data
console.log(error);
}
const myArray = await AsyncStorage.getItem('keyOrdermonan');
if(myArray !=null){
this.state.getArr = JSON.parse(myArray);
//Id food currently
const check = {id:this.state.id};
var position = 0;
//Check id avalilabled in cart ?
const police = this.state.getArr.some(getA => getA.id===check.id );
if(police==true){
for(var i =0;i<this.state.getArr.length;i++){
if(this.state.getArr[i].id==this.state.id){
break;
}else{
position+=1;
}
}
this.state.getArr[position].soluong += this.state.soluong;
this.setState({mangmonan: this.state.getArr});
this.homeref.setSizeCart(this.state.mangmonan.length);
console.log('Completely udrage quanity');
}
else if(police==false){
this.setState({mangmonan: [{id: this.state.id,
soluong: this.state.soluong,
}].concat(this.state.getArr)});
this.homeref.setSizeCart(this.state.mangmonan.length);
}
}else{
this.setState({mangmonan: [{id: this.state.id,
soluong: this.state.soluong,
}]});
this.homeref.setSizeCart(this.state.mangmonan.length);
}
// Add new cart
try {
await AsyncStorage.setItem('keyOrdermonan', JSON.stringify(this.state.mangmonan));
// await AsyncStorage.removeItem('keyOrdermonan');
this.setState({modalVisible:false,soluong:1});
Alert.alert(
"Thành công",
"Đặt món thành công, vui lòng kiểm tra giỏ hàng",
[
{
text: "Kiểm tra giỏ hàng",
onPress: ()=>{this.props.navigation.navigate('cart')}
},
{
text: "Tiếp tục đặt món",
style:'cancel'
},
]
);
} catch (error) {
// Error saving data
console.log(error);
}
}
getPriceVND = (giatri) => {
const parts = giatri.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const gia = parts.join(".");
return gia;
}
rowrender = (type,item) => {
return(
<View style={styles.bgitem}>
<TouchableOpacity style={styles.wrapperitem} onPress={()=> {this.setState({modalVisible:true}),this.openModalWithItem(item)}}>
<View style={styles.wrapperimg}>
<Image source={{ uri: item.hinhanh }} style={styles.img}/>
</View>
</TouchableOpacity>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold' }}>Tên món ăn:</Text>
<Text style={styles.under}>{item.ten}</Text>
</View>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold' }}>Giá: </Text>
<Text style={styles.under}>{this.getPriceVND(item.gia)}đ</Text>
</View>
</View>
)
}
componentDidMount(){
//set lại tittle bar
this.props.navigation.setOptions({title:this.props.route.params.tendanhmuc});
fetch("http://192.168.43.25/DemoJWT/getMonAnByList.php",{
method:'POST',
headers: {
"Accept":"application/json",
"Content-Type":"application/json"
},
body: JSON.stringify({
"IDDANHMUC" : this.props.route.params.id,
})
})
.then((reponse)=>reponse.json())
.then((reponseJson)=>{
if(reponseJson==""){
this.setState({statusInform:true});
}else{
this.setState({
mang:reponseJson,
dataProvider:this.state.dataProvider.cloneWithRows(reponseJson),
})
}
})
.catch((err)=>{
console.log(err);
})
}
render(){
return(
<View style={styles.wrapper}>
{!this.state.hide && <Home ref={this.homeref} />}
{ !this.state.dataProvider.getSize()==0 &&
<RecyclerListView
layoutProvider={this.layoutProvider}
rowRenderer={this.rowrender}
dataProvider = {this.state.dataProvider}
/>
}
{/* Thông báo khi không có món */}
<Snackbar
visible={this.state.statusInform}
onDismiss={()=>{this}}
action={{
label: 'Trở về',
onPress: () => {
this.props.navigation.goBack()
},
}}>
Hiện nhà hàng chưa có các món ăn này.
Mong quý khách thông cảm !
</Snackbar>
{/* Thông báo khi không có món */}
{/* Hiển thị khi nhấn chi tiết món ăn để đặt hàng */}
<View>
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
>
<View style={styles.modalView}>
<View style={styles.wrapperimgModal}>
<Image source={{ uri: this.state.hinhanh }} style={styles.imgModal}/>
<View style={styles.wrappername,{marginTop:15}}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Tên món ăn:</Text>
<Text >{this.state.ten}</Text>
</View>
<View style={{ flexDirection:'column' }}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Giá: </Text>
<Text>{this.getPriceVND(this.state.gia)} đ / 1 phần</Text>
</View>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Mô tả:</Text>
<Text>{this.state.mota}</Text>
</View>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Số lượng:</Text>
<View style={{ flexDirection:'row',marginLeft:0,marginTop:10 }}>
<TouchableOpacity style={styles.decrease} onPress={()=>{
if(this.state.soluong==1){
console.log('Không giảm nữa');
}else{
this.setState({soluong:this.state.soluong-1})
}
}}>
<MaterialCommunityIcons name='minus-circle' color="black" size={24} />
</TouchableOpacity>
<Text>{this.state.soluong}</Text>
<TouchableOpacity style={styles.increase} onPress={()=>{
if(this.state.soluong==15){
console.log('Không tăng nữa');
}
else{
this.setState({soluong:this.state.soluong+1})
}
}}>
<MaterialCommunityIcons name='plus-circle' color="black" size={24} />
</TouchableOpacity>
</View>
</View>
</View>
<View style={styles.totalbtn}>
<View style={styles.btn}>
<Button
title="Hủy"
onPress={()=>{this.setState({modalVisible:false,soluong:1})}}
/>
</View>
<View style={styles.btn2}>
<Button title="Đặt ngay"
onPress={()=>{this._datmon()}}
/>
</View>
</View>
</View>
</Modal>
</View>
{/* Hiển thị khi nhấn chi tiết món ăn để đặt hàng */}
</View>
)
}
}
const styles = StyleSheet.create({
wrapper:{
flex:1,
},
wrapperitem:{
flex:1,
},
title:{
fontSize:30,
padding:10,
fontWeight:'bold',
},
bgitem:{
flex:1,
flexDirection:'column',
padding:10,
margin:10,
borderWidth:1,
borderRadius:15,
backgroundColor:'#dddddd',
},
wrapperimg:{
width:"100%",
height:180,
alignItems:'center',
padding:5,
},
wrapperimgModal:{
width:"100%",
height:370,
padding:5,
marginLeft:10,
},
img:{
width:'80%',
height:100,
borderRadius:10,
},
imgModal:{
width:'100%',
height:150,
borderRadius:10,
},
wrappername:{
flexDirection:'column',
},
under:{
paddingLeft:10,
},
modalView: {
margin: 20,
marginTop:100,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
totalbtn:{
flexDirection:'row',
alignItems:'center',
justifyContent:'center'
},
btn:{
width:90,
marginRight:10,
},
btn2:{
width:90,
marginLeft:10,
},
decrease:{
marginRight:10,
},
increase:{
marginLeft:10
}
})
Still here is your code setSizeCart() in class component Home.js :
import React, { Component } from "react";
import {StyleSheet, Alert,View, StatusBar,Linking, Text} from "react-native"
import AsyncStorage from '#react-native-community/async-storage';
import HomeScreen from "./Screen/HomeScreen";
import FavouriteScreen from "./Screen/FavouriteScreen";
import ProfileScreen from "./Screen/ProfileScreen";
import CartScreen from "./Screen/CartScreen";
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { Appbar, Snackbar,Badge } from 'react-native-paper';
import NetInfo from "#react-native-community/netinfo";
import {createDrawerNavigator} from "#react-navigation/drawer"
import { DrawerActions } from '#react-navigation/native';
import SettingScreen from "./Screen/SettingScreen";
import BookingScreen from "./Screen/BookingScreen";
import FullFood from "./Screen/FullFood";
import 'regenerator-runtime/runtime';
const Drawer = createDrawerNavigator();
export default class Home extends Component{
_isMounted = false;
constructor(props){
super(props);
this.state={
token:"",
ten:"",
statusInform:false,
searchQuery:"",
getMangAsync:[],
itemcart: 0 ,
}
this.setSizeCart = this.setSizeCart.bind(this);
}
setSizeCart (bien){
try {
this.setState({ itemcart: bien });
console.log("set thành công");
} catch (error) {
console.log(error);
}
}
_getasyc = async()=>{
try {
const key = await AsyncStorage.getItem("keyOrdermonan");
if(key!==null){
this.setState({getMangAsync:JSON.parse(key)});
this.setState({itemcart:this.state.getMangAsync.length});
}
} catch (error) {
console.log(error)
}
}
checkInternet(){
NetInfo.fetch("http://192.168.43.25/DemoJWT/checkToken.php")
.then(state=>{
console.log(state.isConnected)
if(state.isConnected==false){
this.setState({statusInform:true})
}
})
}
componentDidMount(){
this._isMounted = true;
if(this._isMounted){
this.checkInternet();
this._getasyc();
}
}
componentWillUnmount(){
this._getasyc();
// console.log("đã"+ this._isMounted)
}
_logout = async() =>{
try {
await AsyncStorage.removeItem("keyToken");
Alert.alert("Đăng xuất");
this.props.navigation.navigate('login');
} catch (error) {
console.log(error)
}
}
contact(){
Alert.alert(
"Liên hệ với chúng tôi",
"Bạn có muốn hay không?",
[
{
text: "Hủy",
style:'cancel'
},
{
text: "Đồng ý",
onPress: ()=>Linking.openURL('tel:$+84705982473')
}
]
)
}
render(){
// const {ten} = this.props.route.params
return(
<View style={{ flex:1 }}>
<StatusBar backgroundColor='#555555' barStyle="light-content" />
<Appbar style={styles.appbar}>
<Appbar.Action icon="format-list-bulleted" onPress={()=>(this.props.navigation.dispatch(DrawerActions.openDrawer()))}/>
<Appbar.Content title="GREAT FOOD" />
<Badge
visible={this.state.itemcart && this.state.itemcart >0}
size={17}
style={{ position: 'absolute', top: 5, right: 55 }}>{this.state.itemcart}</Badge>
<Appbar.Action icon="cart" onPress={()=>{this.props.navigation.navigate('cart')}}/>
<Appbar.Action icon="phone-in-talk" onPress={()=>{this.contact()}}/>
</Appbar>
<Drawer.Navigator
overlayColor="transparent"
>
<Drawer.Screen name ="home" component={HomeScreen}
options={{
drawerLabel:"Menu",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="home" color={color} size={26} />
), }}
/>
<Drawer.Screen name="profile" component={ProfileScreen}
options={{
drawerLabel:"Hồ sơ",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="account-circle" color={color} size={26} />
), }}
/>
<Drawer.Screen name="fullfood" component={FullFood}
options={{
drawerLabel:"Tất cả món ăn",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="food" color={color} size={26} />
), }}
/>
<Drawer.Screen name= "favourite" component={FavouriteScreen}
options={{
drawerLabel:"Yêu thích",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="heart-pulse" color={color} size={26} />
), }}
/>
<Drawer.Screen name= "booking" component={BookingScreen}
options={{
drawerLabel:"Đặt bàn",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="table-furniture" color={color} size={26} />
), }}
/>
<Drawer.Screen name="cart" component={CartScreen}
options={{
drawerLabel:"Giỏ hàng",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="cart" color={color} size={26} />
), }}
/>
<Drawer.Screen name="setting" component={SettingScreen}
options={{
drawerLabel:"Cài đặt",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="wrench-outline" color={color} size={26} />
), }}
/>
</Drawer.Navigator>
<Snackbar
visible={this.state.statusInform}
onDismiss={()=>{this}}
action={{
label: 'Tắt',
onPress: () => {
this.setState({statusInform:false})
},
}}>
Vui lòng kiểm tra kết nối.
</Snackbar>
</View>
)
}
}
const styles = StyleSheet.create({
wrapper:{
flex:1,
justifyContent:"center",
alignItems:'center',
},
logout:{
marginTop:50,
},
appbar:{
backgroundColor:'#555555'
},
})
And I have been received warning is:
Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the Home component.
Can anyone help me!
So one small thing you are missing here is that,
Creating a new component using the new keyword is not going to mount that component into the render tree.
You should include it inside the render function of your FoodByList like this
<Home ref={this.homeRef} />
Then, in the constructor of your FoodByList component, create the homeRef using
this.homeRef = React.createRef();
More on React.createRef in this article.
Basically assigning a ref to the Home component inside the render of FoodByList gives you the ability to call the functions inside the Home component.
Next, in Home component's constructor use this.setSizeCart = this. setSizeCart.bind(this) or else convert the setSizeCart function into an arrow function like this
setSizeCart = (bien) => {
try {
this.setState({ itemcart: bien });
console.log("set successfully");
} catch (error) {
console.log(error);
}
}
So now, instead of doing
this.home.setSizeCart(this.state.mangmonan.length)
you should be doing
this.homeRef.current.setSizeCart(this.state.mangmonan.length)
In the React Native application, the button continues to operate when the information is entered incorrectly on the member entry and registration page. The button is not activated again to re-enter information. Could you help?
In other words, when the information is entered incorrectly or missing, the registration button is rotating continuously.
Please review the screenshot and codes.
Screenshot:
[![Screen shot with the UI][1]][1]
My codes are:
import React from 'react';
import { StyleSheet, Text, View, Image, Dimensions, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/Ionicons';
const { height, width } = Dimensions.get('window');
const LogoImg = require('../assets/img/challengelogo.png');
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scrollview'
import {connect} from 'react-redux';
import * as appActions from './actions';
export class signupView extends React.Component {
constructor(props){
super(props);
this.state = {
checkboxChecked: false,
checkboxIcon: 'ios-square-outline'
}
}
render() {
const { container, innerContainer, innerImageContainer, buttonView , buttonViewRegister, innerButtonTextView, innerButtonView, termsView} = styles;
return (
<LinearGradient
colors={['#f9a149', '#e86e52', '#d6375c']}
style={ container }>
<KeyboardAwareScrollView
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="always"
style={styles.scrollContainer}>
<View style={innerContainer}>
<Image
source={LogoImg}
style={{ width: width*0.45, height: width*0.55 }}
resizeMode={'contain'}
/>
<View style={{flexDirection:'row', alignItems:'center'}}>
<Text style={{color:'#fff', fontSize:18, margin:10, textDecorationLine:'underline'}} >KAYIT OL</Text>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-person-add" size={30} color="#000"/>
<TextInput
style={styles.input}
placeholder="Kullanıcı Adı"
underlineColorAndroid="transparent"
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_name}
onChangeText={this._onNameChanged.bind(this)}
autoFocus = { true }
blurOnSubmit = { false }
returnKeyType = { "next" }
onSubmitEditing = {() => {this.mailTextInput.focus()} }
/>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-mail-outline" size={30} color="#000"/>
<TextInput
ref={(input) => { this.mailTextInput = input; }}
style={styles.input}
placeholder="Mail Adresi"
underlineColorAndroid="transparent"
keyboardType="email-address"
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_email}
onChangeText={this._onEmailChanged.bind(this)}
blurOnSubmit = { false }
returnKeyType = { "next" }
onSubmitEditing = {() => {this.passwordTextInput.focus()} }
/>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="md-lock" size={30} color="#000"/>
<TextInput
ref={(input) => { this.passwordTextInput = input; }}
style={styles.input}
placeholder="Şifre"
onChangeText={(searchString) => {this.setState({searchString})}}
underlineColorAndroid="transparent"
secureTextEntry={true}
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_password}
onChangeText={this._onPasswordChanged.bind(this)}
/>
</View>
{ !this.props.isloadingSignup &&
<TouchableOpacity onPress={this._onSignUpPress}>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<Text style={{ color:'#FFF', fontSize: 15}}>Kayıt Ol</Text>
</View>
</View>
</TouchableOpacity>
||
<TouchableOpacity>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<ActivityIndicator color="white" size='small' />
</View>
</View>
</TouchableOpacity>
}
<TouchableOpacity onPress={this._onPressTerms}>
<View style={ [termsView]}>
<Icon name={this.state.checkboxChecked ? 'ios-checkbox': 'ios-square-outline'} size={30} color="#000" />
<Text style={{ color:'#FFF', fontSize: 15, marginLeft: 10}}><Text onPress={this._onPressTermsConditions } style={{ textDecorationLine: "underline"}}> Kullanım koşullarını</Text> Kabul Ediyorum.</Text>
</View>
</TouchableOpacity>
</View>
</KeyboardAwareScrollView>
</LinearGradient>
);
}
_onSignUpPress = () => {
if(this.state.checkboxChecked) {
var registerBody = {
email: this.props.r_email,
password: this.props.r_password,
password_confirmation: this.props.r_password,
name: this.props.r_name
};
this.props.dispatch(appActions.register(registerBody));
} else {
alert("Lütfen önce Kullanıcı şartlarını kabul edin.");
}
}
_onEmailChanged = (email) => {
this.props.dispatch(appActions.emailChanged(email));
}
_onNameChanged = (name) => {
this.props.dispatch(appActions.nameChanged(name));
}
_onPasswordChanged = (password) => {
this.props.dispatch(appActions.passwordChanged(password));
}
_onPressTerms = () => {
this.setState({ checkboxChecked: !this.state.checkboxChecked })
}
_onPressTermsConditions = () => {
this.props.navigator.push({
screen: 'challenge.TermsOfUse',
navigatorStyle: {
navBarHidden: true
}
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
scrollContainer:{
flex: 1,
},
innerContainer:{
flexDirection:'column',
alignItems:'center',
marginTop: height*0.08,
},
searchSection: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
width:width*0.7,
marginTop:7
},
searchIcon: {
paddingTop:5,
paddingBottom:5,
paddingLeft:10,
paddingRight:10
},
input: {
flex: 1,
backgroundColor: '#fff',
color: '#424242',
justifyContent:'center',
},
buttonView:{
width: width*0.7,
marginTop:20,
flexDirection:'row',
},
buttonViewRegister:{
backgroundColor:"#2b74a7"
},
innerButtonView:{
backgroundColor:'#bab9b9',
width:45,
height:42,
justifyContent:'center',
alignItems:'center'
},
innerButtonTextView:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
termsView:{
width: width*0.8,
marginTop:20,
flexDirection:'row',
justifyContent:'center',
alignItems:'center'
}
});
const mapStateToProps = ({ signup }) => {
return { r_email, r_password, r_name, isloadingSignup } = signup;
};
export default connect(mapStateToProps)(signupView);
Firstly, thanks for your response. I couldn't put the codes here because it crossed the character limit. So you can review the action content from this link. http://karahankaraman.com/actions/index.js
I think you are overcomplicating your signup page. Do you really need to dispatch to redux to handle your signup logic? You might need to show us your actions.js file if this continues.
Meanwhile do this:
{ !this.props.isloadingSignup ?
<TouchableOpacity onPress={this._onSignUpPress}>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<Text style={{ color:'#FFF', fontSize: 15}}>Kayıt Ol</Text>
</View>
</View>
</TouchableOpacity>
:
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<ActivityIndicator color="white" size='small' />
</View>
</View>
}
I am using createDrawerNavigator and inside this I made a custom profile view. When I press navigate I want to move to another screen.
But this give me an error undefined is not an object (evaluating"_this.props.navigation"). Other components one, two, three works fine.
This is my code:
export default class App extends Component {
render() {
return (
<View style={{flex:1, marginTop:30}}>
<AppContainer/>
</View>
);
}
}
const CustomDrawerContentComponent = (props)=> {
return(
<SafeAreaView style={{flex:1}}>
<View style={{ height:100, backgroundColor: '#9FA8DA' }}>
<Image
style={{marginLeft:20,height:100,width:100,borderRadius:50}}
source={require('./assets/puppy.jpg')}/>
</View>
<View style={{flexDirection:'row', margin:20, alignItems:'center'}}>
//////here is where I get an error
<TouchableOpacity
style={{marginTop:0}}
onPress={()=> {this.props.navigation.navigate('profile')}}>
<Text style={{fontSize:18, fontWeight:'bold'}}>navigate</Text>
<Image
style={{height:12,width:12}}
source={require('./assets/drawable-hdpi/ic_arrow_depth.png')}/>
</TouchableOpacity>
</View>
<ScrollView>
<DrawerItems {...props}/>
</ScrollView>
</SafeAreaView>
)
}
const AppDrawerNavigator = createDrawerNavigator({
one: AppStackNavigator,
two: BoardScreen,
three: NotificationScreen,
},{
contentComponent:CustomDrawerContentComponent,
})
const AppStackNavigator = createStackNavigator({
profile: {
screen: profileScreen,
navigationOptions: {
header: null
},
},
})
const StartSwitchNavigator = createSwitchNavigator(
{
App: AppDrawerNavigator,
},
{
initialRouteName: 'App',
}
)
Your CustomDrawerContentComponent component is functional component. Use props.navigation directly instead of this.props
I'm trying to hide a header in a BottomTabNavigator but this one came from a StackNavigator. I already tried to use the header: null inside the page and other ways but nothing works!
const AppTabNav = createBottomTabNavigator({
HomeScr:{
screen:Home,navigationOptions:{tabBarLabel:'Inicio',tabBarIcon: ({tintColor}) => (<Icon name='home' color={tintColor} size={25}/>)}
},
Settings:{
screen:Config,navigationOptions:{ tabBarLabel:'Configurações',tabBarIcon:({ tintColor })=>(<Icon name="settings" color={tintColor} size={25}/>)}
}
})
const AppStackNavigator = createStackNavigator({
AppTab:{
screen:AppTabNav,
navigationOptions:({navigation}) =>({
title:'Bem vindo #USER',
headerLeft:(
<TouchableOpacity onPress={() => navigation.toggleDrawer()}>
<View style={{paddingHorizontal:10}}>
<Icon name="menu" color='black' size={24}/>
</View>
</TouchableOpacity>)
})
}
},{tabBarOptions:{
activeTintColor:'blue',
inactiveTintColor:'black'
}})
This is the header I want to hide when I click on configurações in the Bottombar
Imagem
This is the code of the Config.js file
export default class Config extends Component {
static navigationOptions = {
header: null,
drawerIcon: ({ tintColor }) => ( <Icon name='settings' style={{color:tintColor ,fontSize:24}} />)
}
SignOut = async() => {
AsyncStorage.clear()
this.props.navigation.navigate('AuthLoading')
}
render() {
return (
<Container>
<Header>
<Left style={{flex:1}}>
<Icon name="menu" color='black' size={24} onPress={() => this.props.navigation.openDrawer()}/>
</Left>
<Body style={{flex: 1,justifyContent: 'center'}}>
<Title>Configurações</Title>
</Body>
<Right style={{flex:1}}/>
</Header>
<View style={{flex :1, alignItems:'center', justifyContent:'center'}}>
<Text>Configurações</Text>
</View>
</Container>
);
}
}
Just add this into your component code and Header will be hidden
tabBarVisible: false
export default class Config extends Component {
static navigationOptions = {
tabBarVisible: false,
drawerIcon: ({ tintColor }) => ( <Icon name='settings' style={{color:tintColor ,fontSize:24}} />)
}
SignOut = async() => {
AsyncStorage.clear()
this.props.navigation.navigate('AuthLoading')
}
render() {
return (
<Container>
<Header>
<Left style={{flex:1}}>
<Icon name="menu" color='black' size={24} onPress={() => this.props.navigation.openDrawer()}/>
</Left>
<Body style={{flex: 1,justifyContent: 'center'}}>
<Title>Configurações</Title>
</Body>
<Right style={{flex:1}}/>
</Header>
<View style={{flex :1, alignItems:'center', justifyContent:'center'}}>
<Text>Configurações</Text>
</View>
</Container>
);
}
}