how to make initialParams updated - reactjs

I want to update initialParams of react native navigation on clicking of the menu item
import React, { useState } from 'react';
import {createStackNavigator} from '#react-navigation/stack'
import { NavigationContainer } from '#react-navigation/native';
import userMain from './../../components/users/userMain';
import { View, Icon } from 'native-base';
export const UserStack = () => {
const Stack = new createStackNavigator()
const [toggleSearch, setToggleSearch] = useState(true)
const changeStyleToggle = () => {
setToggleSearch( !toggleSearch )
// console.log('toggle search here ==== ', toggleSearch)
}
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="User Homepage"
component={userMain}
initialParams={{ toggleSearch: toggleSearch}}
options = {{
title: 'My home',
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
headerRight: () => (
<View style={{flexDirection:'row', justifyContent:'space-evenly', width:120}}>
<Icon name='home' onPress={() => changeStyleToggle()} />
<Icon name='home' />
<Icon name='home' />
</View>
),
}}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
the component i am calling is userMain where i am calling initialParams value and on behalf of that i want to change style
import React from 'react'
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native'
import { Input } from 'native-base';
const userMain = (props) => {
const {toggleSearch} = props.route.params;
console.log(toggleSearch)
const check = toggleSearch == true ? 'true!!' : 'false!!'
return (
<View style={styles.container}>
<Input
placeholder="search"
style={styles.searchInput}
/>
<Text>user homepage here</Text>
<Text>{check}</Text>
<TouchableOpacity style={styles.btn}>
<Text style={styles.btnText}> + </Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
container: {
alignItems: 'center', flex: 1, justifyContent: 'center',
},
btn: {
position: 'absolute', justifyContent: 'center', alignItems: 'center',
bottom:10, right:10, width:60, height: 60,
backgroundColor: '#fff', borderRadius: 50, borderColor: '#000',borderWidth:1,
},
btnText: {
fontSize: 50, color: 'black',
},
searchInput: {
position:'absolute', top: 0, borderWidth: 1, width: 300, opacity:0
}
})
export default userMain
i have checked on clicking the icon state which is toggleSearch is updating but it is not updating the initialParams hence it is not working on userMain component as well .

Related

Data exists, but the map function returns no value React Native

I guess I'm not realizing something. I have the structure where I list the friends of the logged in user. Data appears to exist on console.log, but the map function does not work. Also, when I press the component in tab transitions, useEffect only works once. It doesn't work after that. Can you help me? Thanks.
App.js code
import { StatusBar } from 'expo-status-bar';
import React, { useState, useMemo } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import SignIn from './SignIn';
import SignUp from './SignUp';
import Conversation from './Conversation';
import Contacts from './Contacts';
import Settings from './Settings';
import Chats from './Chats';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import {Ionicons} from '#expo/vector-icons'
import { UserProvider } from './UserContext';
import { LogBox } from "react-native"
const Stack = createNativeStackNavigator();
const Tabs = createBottomTabNavigator();
const TabsNavigator = () => (
<Tabs.Navigator screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
return <Ionicons name={route.name === "Chats" ? "chatbubble-ellipses-outline" : route.name === "Contacts" ? "people-outline" : "settings-outline"} color={color} size={size} />
}})}>
<Tabs.Screen name="Chats" component={Chats} />
<Tabs.Screen name="Contacts" component={Contacts} />
<Tabs.Screen name="Settings" component={Settings} />
</Tabs.Navigator>
);
export default function App() {
LogBox.ignoreAllLogs(true);
// const [lastUser, setLastUser] = useState('none');
// const value = useMemo(
// () => ({ lastUser, setLastUser }),
// [lastUser]
// );
return (
<UserProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen options={{headerShown : false }} name="SignIn" component={SignIn} />
<Stack.Screen
name="SignUp"
component={SignUp}
options={{ headerTitle:'Login', headerBackVisible : true, headerBackTitleVisible :true}}
/>
<Stack.Screen name="Home" component={TabsNavigator} options={{headerShown : false, headerBackTitleVisible : false}}/>
<Stack.Screen name="Contacts" component={Contacts} options={{ headerTitle:'ChatApp'}}/>
<Stack.Screen name="Conversation" component={Conversation} options={{ headerTitle:'ChatApp'}}/>
</Stack.Navigator>
</NavigationContainer>
</UserProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
SignIn.js code
import { useNavigation } from '#react-navigation/core'
import React, { useEffect, useState, createContext, useContext } from 'react'
import { KeyboardAvoidingView, StyleSheet, Text, TextInput, TouchableOpacity, View, Image } from 'react-native'
import { borderColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes'
import { auth, firebase } from './firebase'
import { userContext } from './UserContext'
import AsyncStorage from '#react-native-async-storage/async-storage';
const SignIn = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const navigation = useNavigation()
const value = useContext(userContext);
const handleLogin = async() => {
await auth
.signInWithEmailAndPassword(email, password)
.then(userCredentials => {
const user = userCredentials.user;
console.log('Logged in with:', user.email);
getUser(user.email);
navigation.replace("Home");
})
.catch(error => alert(error.message))
}
const getUser = async (email2) => {
await firebase.database().ref().child('users').orderByChild('email').equalTo(email2).once('value').then((data) => {
data.forEach((node) => {
storeUser(node.val().username); // one data
}
)
}
)
}
const storeUser = async(data) => {
try{
await AsyncStorage.setItem('sertacKul', data);
}catch(err){
console.log(err);
}
}
return(
<KeyboardAvoidingView
style={styles.container}
behavior="padding"
>
<View style={styles.inputContainer}>
<Image style={styles.logo} source={require('./img/logo.png')}>
</Image>
<TextInput
placeholder="Email"
value={email}
onChangeText={text => setEmail(text)}
style={styles.input}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={text => setPassword(text)}
style={styles.input}
secureTextEntry
/>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={handleLogin}
style={styles.button}
>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={handleSignUp}
onPress={() => navigation.navigate('SignUp')}
style={[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>Register</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={handleSignUp}
onPress={() => value.setData('ebebbebebe')}
style={[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>{value.lastUser}</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
)
}
export default SignIn;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor : 'white'
},
logo :{
resizeMode :'contain',
width: '100%',
marginBottom : 40
},
inputContainer: {
width: '80%'
},
input: {
backgroundColor: '#eeeeee',
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
},
buttonContainer: {
width: '60%',
justifyContent: 'center',
alignItems: 'center',
marginTop: 40,
},
button: {
backgroundColor: '#06d6cc',
width: '100%',
padding: 15,
borderRadius: 10,
alignItems: 'center',
},
buttonOutline: {
backgroundColor: 'white',
marginTop: 5,
borderColor: '#06d6cc',
borderWidth: 2,
},
buttonText: {
color: 'white',
fontWeight: '700',
fontSize: 16,
},
buttonOutlineText: {
color: '#06d6cc',
fontWeight: '700',
fontSize: 16,
},
})
Contact.js code
import React, { useState, useEffect, useContext } from "react";
import {
StyleSheet,
View,
TextInput,Text
} from "react-native";
import { auth, firebase } from "./firebase";
import { List, Avatar, Divider, FAB } from "react-native-paper";
import uuid from "react-native-uuid";
import moment from "moment";
import { userContext } from "./UserContext";
import AsyncStorage from '#react-native-async-storage/async-storage';
const Contacts = () => {
const [username, setUsername] = useState("");
const value = useContext(userContext);
const [contactList, setContactList] = useState([{}]);
const [lastUser, setLastUser] = useState('');
useEffect(() => {
setContactList([])
updateLastUserName();
getContacts();
}, [])
useEffect(() => {
console.log(lastUser);
console.log(contactList);
}, [lastUser, contactList]);
async function updateLastUserName(){
const user = await getUserName();
setLastUser(user);
}
async function getUserName(){
const user = await AsyncStorage.getItem('sertacKul');
return user;
}
const addFriend = () => {
console.log(value.lastUser)
firebase
.database()
.ref("/users/")
.once("value")
.then((data) => {
let id = uuid.v4();
firebase
.database()
.ref("/friendrelations/" + id)
.set({
id: id,
user1: username,
user2: lastUser,
relationtype: "normal",
createdDate: moment().format("DD/MM/YYYY HH:mm:ss"),
})
.then(() => alert("Friend added."));
});
};
async function getContacts(){
await firebase.database().ref().child('friendrelations').orderByChild('user2').equalTo(lastUser)
.once('value').then(data => {
data.forEach((node) => { setContactList(lastContacts => [...lastContacts, node.val().user1])})
})
}
return (
<View>
<TextInput
placeholder="Yeni Arkadaş"
value={username}
style={styles.input}
onChangeText={(text) => setUsername(text)}
/>
<FAB
onPress={() => addFriend()}
icon="plus"
style={{ position: "absolute", right: 16 }}
/>
{/* is not working */}
{contactList.map((item)=>{
(<List.Item onPress={() => navigation.navigate('Conversation')} title={item}
left={() => <Avatar.Image source={require('./img/profile1.png')} size={53}/>}
/>
)
})}
<Divider inset/>
</View>
);
};
export default Contacts;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "white",
},
logo: {
resizeMode: "contain",
width: "100%",
marginBottom: 40,
},
inputContainer: {
width: "80%",
},
input: {
backgroundColor: "#eeeeee",
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
},
buttonContainer: {
width: "60%",
justifyContent: "center",
alignItems: "center",
marginTop: 40,
},
button: {
backgroundColor: "#06d6cc",
width: "100%",
padding: 15,
borderRadius: 10,
alignItems: "center",
},
buttonOutline: {
backgroundColor: "white",
marginTop: 5,
borderColor: "#06d6cc",
borderWidth: 2,
},
buttonText: {
color: "white",
fontWeight: "700",
fontSize: 16,
},
buttonOutlineText: {
color: "#06d6cc",
fontWeight: "700",
fontSize: 16,
},
});
The arrow function has a function body and neglects to return any value that is being mapped to. Don't forget to also specify a unique React key for the mapped components/elements.
{contactList.map((item) => {
return (
<List.Item
key={item.id}
onPress={() => navigation.navigate('Conversation')}
title={item}
left={() => <Avatar.Image source={require('./img/profile1.png')} size={53}/>}
/>
);
})}
Or remove the body so there's an implicit return.
{contactList.map((item) => (
<List.Item
key={item.id}
onPress={() => navigation.navigate('Conversation')}
title={item}
left={() => <Avatar.Image source={require('./img/profile1.png')} size={53}/>}
/>
))}

Adding Custom header in react-navigation 5

I know how to implement header in navigation 3, but I'm having trouble passing the navigation to my header component in version 5.
(HomeStack.js)
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { Button } from 'react-native';
import Home from '../screens/home';
import ReviewDetails from '../screens/reviewDetails';
import Header from '../shared/header';
const Stack = createStackNavigator()
export default Navigator = () => {
return (
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}
>
<Stack.Screen
name='Home'
component={Home}
options={{
headerTitle: ({navigation}) => <Header navigation={navigation}/>
}}
/>
<Stack.Screen name='ReviewDetails' component={ReviewDetails} />
</Stack.Navigator>
)
}
(header.js)
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { MaterialIcons } from '#expo/vector-icons';
export default function Header({ navigation }) {
const openMenu = () => {
navigation.openDrawer();
}
return (
<View style={styles.header}>
<MaterialIcons name='menu' size={28} onPress={openMenu} style={styles.icon}/>
<View>
<Text style={styles.headerText}>GameZone</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
header: {
width: '100%',
height: '100%',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
headerText: {
fontWeight: 'bold',
fontSize: 20,
color: '#333',
letterSpacing: 1,
},
icon: {
position: 'absolute',
left: 16
}
});
I think the only problem is how to pass the navigation var. to the header component in order to open and close the drawer. I am struggling with this problem. Your help is appreciated.

React Native Navigation (ver4.x) unable to get props in custom header component. Keep getting undefined error

I have a custom header in my app and I am trying to get the navigation to open the Drawer when clicked on the menu item in the header component. I've passed the navigation and the header text as props to the component. However the props are being returned as undefined.
This is my header
import React from 'react';
import {View, StyleSheet, Text, Image, Alert, TouchableOpacity } from 'react-native';
import Colors from '../constants/Colors';
import { MaterialIcons } from '#expo/vector-icons';
const Header = ({navigation, headerText}) => {
const openMenu = () => {
console.log({headerText}) **/// this prints Object { "headerText": undefined,}**
navigation.openDrawer() **/// this also throws an undefined error**
}
console.log(headerText)**/// this displays the headerText correct on loading**
return (
<View style={styles.header} >
<MaterialIcons onPress={openMenu} name='menu' size={30} style={styles.icon} />
<Text style={styles.logo}>My Home Page Header</Text>
</View>
);
};
const styles = StyleSheet.create({
header: {
paddingTop: 20,
width: '100%',
height: '10%',
flexDirection: 'row',
},
logo: {
height: '100%',
width: '90%',
fontFamily: 'pacifico-regular',
fontSize: 28,
paddingTop: 20,
paddingLeft: 20,
},
icon: {
marginTop:30,
paddingLeft: 10,
},
});
export default Header;
console.log(headerText)/// this displays the header text correctly when loading the component.
However trying to use the props in the Text or the View throws an undefined error.
Clicking on the MaterialIcon menu icon gives the error :
Object {
"headerText": undefined,
}
and
TypeError: undefined is not an object (evaluating 'navigation.openDrawer')
This is the homestack.js
import { createStackNavigator } from 'react-navigation-stack';
import NewFeaturedRecipes from '../screens/NewFeaturedRecipes';
import NewRecipeDetails from '../screens/NewRecipeDetails';
import Header from '../shared/Header';
import React from 'react';
import {navigation} from 'react-navigation'
// const navigation = navigation;
const screens = {
NewFeaturedRecipes: {
screen: NewFeaturedRecipes,
navigationOptions: ({navigation}) => {
return {
headerTitle: () => <Header navigation={navigation}
headerText='Testting headertext from hoomestack' />
}
}
},
NewRecipeDetails: {
screen: NewRecipeDetails,
navigationOptions: {
title: 'Recipe Details',
}
},
}
const HomeStack = createStackNavigator(screens, {
defaultNavigationOptions: {
headerStyle: {
height: 20,
},
}
});
export default (HomeStack);
Here the answer if anybody is interested. I've used React Navigation 5.x for the nested navigators and I am able to call the openDrawer() from the menu in the Header component.
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button, DrawerLayoutAndroid } from 'react-native';
import { NavigationContainer, useNavigation } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import {createDrawerNavigator} from '#react-navigation/drawer';
import { MaterialIcons } from '#expo/vector-icons';
const Header = ({ headerText }) => {
const navigation = useNavigation()
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }}>
<MaterialIcons onPress={()=> navigation.openDrawer()} name='menu' size={30} style={styles.icon} />
<Text>Header Text = {headerText}</Text>
</View>
)
}
const HomeScreen = ({ navigation }) => {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button onPress={() => navigation.navigate('Details')} title='Goto Details Screen' />
</View>
)
}
const DetailScreen = ({ navigation }) => {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Detail Screen</Text>
<Button onPress={() => navigation.navigate('Home')} title='Goto Home Screen' />
</View>
)
}
const HomeStack = () => {
return (
<Stack.Navigator>
<Stack.Screen
name='Home'
component={HomeScreen}
options={{
headerTitle: props => <Header headerText='Text from App' />
}}
/>
<Stack.Screen name='Details' component={DetailScreen} options={{
headerTitle: props => <Header headerText='Text from Details' />
}}
/>
</Stack.Navigator>
)
}
function NotificationsScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection:'column' }}>
<Text>Notifications Screen</Text>
<Button onPress={() => navigation.goBack()} title="Go back home" />
</View>
);
}
const Stack = createStackNavigator()
const Drawer = createDrawerNavigator()
const App = () => {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName='Home'>
<Drawer.Screen name='Home' component={HomeStack}/>
<Drawer.Screen name='Notifications' component={NotificationsScreen}/>
</Drawer.Navigator>
</NavigationContainer>
)
}
export default App
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

React Navigation Shared Element 5 Nested Navigators

I'm running into a little issue with react-navigation-shared-element 5, so I made a very basic app to show an example. Basically I have a tab navigator nested in a stack navigator and when navigating to the tab navigator I'd like for a shared element transition. This is what I have so far. The transition was working when I had both MainScreen and OtherScreen in the Stack Navigator, but when I moved OtherScreen to the tab navigator it stopped.
import {NavigationContainer} from '#react-navigation/native';
import MainScreen from './src/MainScreen';
import OtherScreen from './src/OtherScreen';
import OtherScreenSecond from './src/OtherScreenSecond';
import {createSharedElementStackNavigator} from 'react-navigation-shared-element';
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
const Stack = createSharedElementStackNavigator();
const Tab = createBottomTabNavigator();
const TabStuff = () => {
return (
<Tab.Navigator>
<Tab.Screen name="OtherScreen" component={OtherScreen} />
<Tab.Screen name="OtherScreenSecond" component={OtherScreenSecond} />
</Tab.Navigator>
);
};
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator mode="modal" headerMode="none">
<Stack.Screen name="MainScreen" component={MainScreen} />
<Stack.Screen name="Tabs" component={TabStuff} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import {SharedElement} from 'react-navigation-shared-element';
const MainScreen = (props) => {
return (
<View style={{...styles.container}}>
<SharedElement id="test">
<View
style={{
width: 100,
height: 100,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 50,
backgroundColor: 'orange',
marginBottom: 50,
}}></View>
</SharedElement>
<TouchableOpacity onPress={() => props.navigation.navigate('Tabs')}>
<Text>Next</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'red',
},
});
export default MainScreen;
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import {SharedElement} from 'react-navigation-shared-element';
const OtherScreen = (props) => {
return (
<View style={{...styles.container}}>
<SharedElement id="test">
<View
style={{
width: 150,
height: 150,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 75,
backgroundColor: 'blue',
marginBottom: 50,
}}></View>
</SharedElement>
<TouchableOpacity onPress={() => props.navigation.pop()}>
<Text>Back</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'yellow',
},
});
OtherScreen.sharedElements = (route, otherRoute, showing) => {
return ['test'];
};
export default OtherScreen;
Any pointers would be greatly appreciated, thanks!
You have to add sharedElementsConfig to Stack. Screen specifying the id of the shared element to work while navigating back
Change code to:
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator mode="modal" headerMode="none">
<Stack.Screen
name="MainScreen"
sharedElementsConfig={(props) => [
{
id: 'test', animation: 'fade'
}
]}
component={MainScreen} />
<Stack.Screen name="Tabs" component={TabStuff} />
</Stack.Navigator>
</NavigationContainer>
);
};

conditionality render headerRight - React Native

I have to render headerRight conditionally in navigation options.
Right now
static navigationOptions = ({ navigation }) => ({
title: i18N.t('atmbranchpickHeader'),
headerRight: (
<TouchableHighlight
underlayColor="#E22F39"
onPress={() => {
navigation.navigate("home");
}}
>
<Image
style={{ marginRight: 20 }}
source={require('../../resources/toolbar/home_white.png')}
/>
</TouchableHighlight>
),
headerTintColor: "white",
headerStyle: {
backgroundColor: "#E22F39"
// top: 30
}
});
My Component
import React, { Component } from "react";
import {
View,
TextInput,
Text,
TouchableOpacity,
TouchableHighlight,
StyleSheet,
AsyncStorage,
BackHandler,
Image,
FlatList,
Dimensions,
TouchableWithoutFeedback
} from "react-native";
import i18n from "../../i18n/i18n.js";
import { colors } from "../../constants/colors.js";
import Storage from "../../utils/AsyncStorage.js";
class AtmBranchTypeSelect extends Component {
// Render callBack
constructor(props) {
super(props);
this.state = {
data: [
],
stBool: false,
}
}
async componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', () => this.props.navigation.goBack());
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', () => this.props.navigation.goBack());
}
static navigationOptions = ({ navigation }) => ({
title: i18n.t('atmbranchpickHeader'),
headerRight: (
<TouchableHighlight onPress={() => {
navigation.navigate('home');
}}>
<Image style={{ marginRight: 20 }} source={require('../../resources/toolbar/home_white.png')} />
</TouchableHighlight>),
headerTintColor: 'white',
headerStyle: {
backgroundColor: colors.themeColor,
// top: 30
}
});
_renderList = ({ item }) => {
return (
<TouchableWithoutFeedback onPress={(event) => this._selectedItem(item.key)}>
<View style={styles.listRowContainer}>
<View style={styles.listinside1Container}>
<Image style={styles.listImage} source={item.icon} />
<View style={styles.listContainer} onPress={(event) => this._selectedItem(item.text)} >
<Text style={styles.listHeader} >{item.header}</Text>
<Text style={styles.listValue} >{item.value}</Text>
</View>
</View>
<Image style={styles.listimgArrow} source={require('../../resources/toolbar/chevron_right_grey.png')} />
</View>
</TouchableWithoutFeedback>
);
}
// Render callBack
render() {
return (
<View style={styles.mainWrapper} >
<FlatList data={this.state.data} renderItem={this._renderList} />
</View>
);
}
}
const styles = StyleSheet.create({
mainWrapper: {
flex: 1,
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
flexDirection: 'column',
justifyContent: 'flex-start'
},
listRowContainer: {
flexDirection: 'row',
marginTop: 10,
height: 80,
backgroundColor: '#FFFFFF',
justifyContent: 'space-between',
borderBottomWidth: 1,
borderColor: 'lightgray'
},
listinside1Container: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center'
},
listContainer: {
alignItems: 'flex-start',
justifyContent: 'center',
flexDirection: 'column',
backgroundColor: '#FFFFFF',
// borderBottomWidth: 1,
// borderColor: 'lightgray'
},
listHeader: {
color: 'black',
fontFamily: 'Roboto-Medium',
marginLeft: 10,
fontSize: 18,
},
listValue: {
fontFamily: 'Roboto-Regular',
marginTop: 4,
color: 'black',
marginLeft: 10,
fontSize: 14,
},
listImage: {
alignSelf: 'center',
height: 25,
width: 25,
margin: 10
},
listimgArrow: {
// flex: 1,
// flexDirection:'row',
alignSelf: 'center',
height: 25,
width: 25,
margin: 10
},
listVal: {
borderWidth: 1,
borderRadius: 10,
color: 'darkgreen',
borderColor: 'white',
backgroundColor: 'white',
fontWeight: 'bold'
},
});
export default AtmBranchTypeSelect;
From the code I have, headerRight will be displayed in all scenarios. consider I have a scenario like based on state value I have to enable/disable headerRight Button .
for example this.state.stBool? headerRight:(.....) : null
I have to render in this way.Please guide me to achieve this.
You could nest the navigation options inside the render and toggle it based on the state value. Haven't tested and not positively on performace. Hope it helps.
import React, { Component } from "react";
import {
View,
TextInput,
Text,
TouchableOpacity,
TouchableHighlight,
StyleSheet,
AsyncStorage,
BackHandler,
Image,
FlatList,
Dimensions,
TouchableWithoutFeedback
} from "react-native";
import i18n from "../../i18n/i18n.js";
import { colors } from "../../constants/colors.js";
import Storage from "../../utils/AsyncStorage.js";
class AtmBranchTypeSelect extends Component {
// Render callBack
constructor(props) {
super(props);
this.state = {
data: [],
stBool: false
};
}
async componentWillMount() {
BackHandler.addEventListener("hardwareBackPress", () =>
this.props.navigation.goBack()
);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", () =>
this.props.navigation.goBack()
);
}
_renderList = ({ item }) => {
return (
<TouchableWithoutFeedback onPress={event => this._selectedItem(item.key)}>
<View style={styles.listRowContainer}>
<View style={styles.listinside1Container}>
<Image style={styles.listImage} source={item.icon} />
<View
style={styles.listContainer}
onPress={event => this._selectedItem(item.text)}
>
<Text style={styles.listHeader}>{item.header}</Text>
<Text style={styles.listValue}>{item.value}</Text>
</View>
</View>
<Image
style={styles.listimgArrow}
source={require("../../resources/toolbar/chevron_right_grey.png")}
/>
</View>
</TouchableWithoutFeedback>
);
};
// Render callBack
render() {
const { stBool } = this.state;
const navigationOptions = ({ navigation }) => ({
title: i18n.t("atmbranchpickHeader"),
headerRight: stBool ? (
<TouchableHighlight
onPress={() => {
navigation.navigate("home");
}}
>
<Image
style={{ marginRight: 20 }}
source={require("../../resources/toolbar/home_white.png")}
/>
</TouchableHighlight>
) : null,
headerTintColor: "white",
headerStyle: {
backgroundColor: colors.themeColor
// top: 30
}
});
return (
<View style={styles.mainWrapper}>
<FlatList data={this.state.data} renderItem={this._renderList} />
</View>
);
}
}

Resources