How to set the dropdown state to initial whenever I switch Tabs? - reactjs

I have a bottomtabbar with three screens, all the screens are have a dropdown picker at the header.
Whenever I have my dropdown open and I change the tab screen, my dropdown is still remains opened, however I would like my dropdown to remain closed initially whenever I changed tabs.
My exact code is as follows:
import React, {useEffect, useState} from 'react';
import {ActivityIndicator} from 'react-native';
import {SafeAreaView, View, Image, TouchableOpacity} from 'react-native';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
// bottom tab
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
import Icon from 'react-native-vector-icons/FontAwesome';
import DropDownPicker from 'react-native-dropdown-picker';
//tabs component
import HomeTabScreen from './HomeTabScreen';
import ConsultationHomeScreen from '../Consult/ConsultationHomeScreen';
import PlansTabScreen from './PlansTabScreen';
import ChatTabScreen from './ChatTabScreen';
import {useSelector, useDispatch} from 'react-redux';
import {
setSelectedChild,
setSelectedChildId,
} from '../../store/actions/userActions';
import {isValidObject} from '../../utils/baseUtils';
import {getChildFromUserChildrenList} from '../../utils/userUtils';
import {setAppReload} from '../../store/actions/HomeActions';
export default function PLHomeScreen(props) {
const {navigation} = props;
const [loading, setLoading] = useState(false);
const Tab = createBottomTabNavigator();
//child related
const [loadApi, setLoadApi] = useState(true);
//Use for all the dispatch actions
const dispatch = useDispatch();
const User = useSelector((state) => state.userReducer.user);
const mSChildId = useSelector((state) => state.userReducer.selectedChildId);
let mChild = getChildFromUserChildrenList(User, mSChildId);
const defaultchildvalue = getChildFromUserChildrenList(User, mSChildId);
const reloadApp = useSelector(
(state) => state.premiumCardActionTypesReducer.reloadApp,
);
console.log('!!!! Reload App !!!!', reloadApp);
useEffect(() => {
if (!isValidObject(mChild)) {
if (!isValidObject(mSChildId)) {
let cid = User.children[0].id;
handleChangeChild(cid);
}
}
if (loadApi == true) {
setLoadApi(false);
setLoading(false);
}
if (reloadApp == true) {
setLoadApi(true);
setLoading(true);
dispatch(setAppReload(false));
}
console.log('!!!! Reload App !!!!', reloadApp);
}, [User, mSChildId, loadApi, reloadApp]);
const handleChangeChild = (id) => {
dispatch(setSelectedChildId(id));
mChild = getChildFromUserChildrenList(User, id);
setLoadApi(true);
setLoading(true);
};
return (
<SafeAreaView
style={{
flex: 1,
alignItems: 'stretch',
justifyContent: 'center',
backgroundColor: '#FE017E',
}}>
<View>
<View
style={{
height: 56,
backgroundColor: '#FE017E',
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => navigation.openDrawer()}
style={{
backgroundColor: '#FE017E',
width: '100%',
height: 40,
padding: 10,
}}
underlayColor="transparent">
<Icon size={20} name="bars" style={{marginLeft: 2}} color="#fff" />
</TouchableOpacity>
</View>
{User != null &&
User.children != undefined &&
User.children != null &&
User.children.length > 0 &&
mChild &&
mChild != undefined &&
mChild != null && (
<DropDownPicker
items={User.children.map((item) => {
return {
label: item.name + '\n' + item.dob_text,
value: item,
icon: () =>
item.pic_url ? (
<Image
source={{
uri: item.pic_url,
}}
style={{height: 30, width: 30, borderRadius: 15}}
/>
) : item.gender === 'male' ? (
<Image
source={{
uri:
'https://cdn3.iconfinder.com/data/icons/materia-human/24/013_042_newborn_infant_child_baby-512.png',
}}
style={{height: 30, width: 30}}
/>
) : (
<Image
source={{
uri:
'https://cdn3.iconfinder.com/data/icons/materia-human/24/013_042_newborn_infant_child_baby-512.png',
}}
style={{height: 30, width: 30}}
/>
),
};
})}
onChangeItem={(item) => {
if (item.value.id != mSChildId) {
handleChangeChild(item.value.id);
}
}}
containerStyle={{
marginLeft: 60,
marginTop: -46,
marginBottom: 10,
height: 40,
}}
defaultValue={defaultchildvalue}
dropDownStyle={{
backgroundColor: '#ffffff',
marginLeft: 40,
borderColor: 'grey',
borderWidth: 1,
borderBottomEndRadius: 0,
borderBottomLeftRadius: 0,
borderBottomStartRadius: 0,
borderBottomRightRadius: 0,
minWidth: 100,
maxWidth: 150,
}}
itemStyle={{
justifyContent: 'flex-start',
fontWeight: 'bold',
fontSize: 20,
borderColor: '#FE017E',
}}
style={{
backgroundColor: '#FE017E',
borderBottomEndRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
borderBottomStartRadius: 0,
borderTopEndRadius: 0,
borderTopLeftRadius: 0,
borderRadius: 0,
borderColor: '#FE017E',
minWidth: 100,
maxWidth: 150,
}}
labelStyle={{
marginLeft: 15,
fontWeight: 'bold',
fontSize: 10,
color: 'black',
textAlign: 'center',
}}
arrowColor={'white'}
activeLabelStyle={{color: '#FE017E'}}
selectedLabelStyle={{color: 'white'}}
/>
)}
</View>
{loading ? (
<ActivityIndicator
color="#FF1493"
size="large"
style={{
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
flex: 1,
flexDirection: 'row',
}}
/>
) : (
// <View>
<Tab.Navigator
lazy={true}
initialRouteName="Home"
tabBarOptions={{
labelStyle: {
color: '#FF1493',
fontSize: 12,
},
}}>
<Tab.Screen
name="Home"
// uncommnet below line to see new Home Tab
component={HomeTabScreen}
// uncomment below see old Home Tab
// component={HomeScreen}
options={{
tabBarLabel: 'Home',
tabBarIcon: ({}) => (
<MaterialIcon name="home" color="#FF1493" size={30} />
),
}}
/>
<Tab.Screen
name="Consult"
component={ConsultationHomeScreen}
initialParams={{
mSChildId: mSChildId,
}}
options={{
tabBarLabel: 'Consult',
tabBarIcon: ({}) => (
<FontAwesomeIcon name="stethoscope" color="#FF1493" size={30} />
),
}}
/>
{mChild != null && mChild.is_sc_subscribed == true ? (
<Tab.Screen
name="Chat"
component={ChatTabScreen}
options={{
tabBarLabel: 'Chat',
tabBarIcon: ({}) => (
<MaterialCommunityIcons
name="chat-outline"
color="#FF1493"
size={30}
/>
),
}}
/>
) : (
<Tab.Screen
name="Plans"
component={PlansTabScreen}
options={{
tabBarLabel: 'Plans',
tabBarIcon: ({}) => (
<MaterialCommunityIcons
name="crown-outline"
color="#FF1493"
size={30}
/>
),
}}
/>
)}
</Tab.Navigator>
)}
</SafeAreaView>
);
}
Kindly, let me know how do I let my dropdown remain closed whenever I switch tabs.
Any lead would be appreciated.

Define a controller for your dropdown picker then add a custom buttons to your tab navigator. The custom buttons would allow you implement an onPress listener and in the listener you can run controller.close() to close the dropdown picker.
You can check the npm page if you're not familiar with controllers for the dropdown picker
Edit: Here's how to set a controller as per the npm page:
const [value, setValue] = useState(null);
const [items, setItems] = useState([ {...}, ... ]);
let controller;
<DropDownPicker
items={items}
controller={instance => controller = instance}
onChangeList={(items, callback) => {
new Promise((resolve, reject) => resolve(setItems(items)))
.then(() => callback())
.catch(() => {});
}}
defaultValue={value}
onChangeItem={item => setValue(item.value)}
/>
then you can use the controller wherever you want in your code.

Related

React native - dispatching action gets me back to first screen, but it shouldnt

I'been having this odd issue for quite a while. Whenever I dispatch any of action from my context API i get send back to the first screen in Stack Navigation (expo react native).
Is there a way to fix this ?
Files:
context.js
import { createContext } from 'react';
export const AppContext = createContext();
App.js
export default function App() {
const Stack = createNativeStackNavigator();
// GLOBAL STATE
const [alarms, setAlarms] = useState([]);
const dispatchAlarmEvent = (actionType, payload) => {
switch (actionType) {
case 'ADD_ALARM':
setAlarms([ ...alarms, payload ]);
break; // return;
case 'REMOVE_ALARM':
setAlarms([...alarms.filter(alarm => alarm.id !== payload.id)]);
break; // return;
case 'EDIT_ALARM':
setAlarms([...alarms.filter(alarm => alarm.id !== payload.id), payload]);
break; // return;
default:
break; // return;
}
};
const log = (x)=> console.log(x)
return (
<AppContext.Provider value={ { alarms , dispatchAlarmEvent, log} }>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Start" component={Start} options={{
headerShown: false,
title: 'Start',
}} />
<Stack.Screen name="Home" component={Home} options={{
headerStyle: { backgroundColor: Theme.primary },
headerTintColor: 'rgb(243,243,243)',
headerTitleStyle: { fontWeight: 'bold' },
title: 'Alarms List',
}} />
<Stack.Screen name="AddAlarm" component={AddAlarmForm} options={{
headerStyle: { backgroundColor: Theme.primary },
headerTintColor: 'rgb(243,243,243)',
headerTitleStyle: { fontWeight: 'bold' },
title: 'Add Alarm',
}} />
</Stack.Navigator>
</NavigationContainer>
</AppContext.Provider>
)
}
and example of place where I dispatch action:
Item.js
const AlarmItem = (props) => {
const [isEnabled, setIsEnabled] = useState(props.ring);
const [ expanded, toggleExpanded ] = useBool(false);
const [ arrowUpyDowny, setArrowUpyDowny ] = useState(faChevronDown);
const [ height, setHeight ] = useState(new Animated.Value(0))
const { dispatchAlarmEvent } = useContext(AppContext)
const week = ["Mon.", "Tues.", "Wed.", "Thurs.", "Fri.", "Sat.", "Sun."]
const toggle = () => {
const toPos = ( !expanded )? 140 : 0;
Animated.spring(height, {
toValue: toPos,
useNativeDriver: false,
}).start();
toggleExpanded()
}
const deleteItem = () =>{
console.log( props.id )
dispatchAlarmEvent('REMOVE_ALARM', { id: props.id });
Database.remove(props.id)
}
useEffect( ()=> {
}, [isEnabled])
return (
<View style={styles.container}>
<View style={styles.row}>
<Text style={styles.time}> { props.hours } : { props.minutes } </Text>
<Switch
trackColor={{ false: "#767577", true: Theme.primary+'5d' }}
thumbColor={isEnabled ? Theme.primary : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={()=> setIsEnabled(!isEnabled)}
value={isEnabled}
style={{ flex: 1 }}
/>
</View>
<View style={[styles.row, { borderTopWidth: 0 }]}>
<TouchableNativeFeedback
background={TouchableNativeFeedback.Ripple('rgba(255,255,255,1)', true)}
onPress={() => deleteItem()}
style={{
width: 60,
height: 60,
}}
>
<View style={{ margin: 10, width: 50, height: 50, background: "red", justifyContent: 'center', alignItems: 'center', backgroundColor: Theme.primary, borderRadius: 50 }}>
<FontAwesomeIcon icon={ faTrash } color={'#fff'}/>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback
background={TouchableNativeFeedback.Ripple('rgba(255,255,255,1)', true)}
onPress={() => toggle()}
style={{
width: 60,
height: 60,
}}
>
<View style={{ margin: 10, width: 50, height: 50, background: "red", justifyContent: 'center', alignItems: 'center', backgroundColor: Theme.primary, borderRadius: 50 }}>
<FontAwesomeIcon icon={ (!expanded)? faChevronDown: faChevronUp } color={'#fff'}/>
</View>
</TouchableNativeFeedback>
</View>
<Animated.View style={{
height: height, // animowany styl, tutaj wysokość View
// backgroundColor: "#FF0000",
}} >
{
(expanded) && (<View style={styles.unfolded}>
{
props.days.map( (day,i)=> ( <TouchableNativeFeedback
key={i}
background={TouchableNativeFeedback.Ripple('rgba(255,255,255,1)', true)}
onPress={() => alert('xx')}
style={{
width: 30,
height: 30,
}}
>
<View style={{ margin: 3, width: 50, height: 50, justifyContent: 'center', alignItems: 'center', color: '#fff', backgroundColor: (day)? Theme.lighter: 'rgba(255,255,255,.3)', borderRadius: 50, }}>
<Text style={{color: '#fff'}}> { week[i] } </Text>
</View>
</TouchableNativeFeedback> ))
}
</View>)
}
</Animated.View>
</View>
)
}
Please if you have any clues? or perhaps i am doing sth wrong. Thx in advance

CustomDrawerNavigator: Change Active and Inactive Background Colour

On react-navigation/drawer's DrawerItem, is there a way to add active and inactive background colour? I followed this document to implement this https://reactnavigation.org/docs/drawer-navigator/.
I have added theses code lines to the drawerItems. But it won't work for me.
drawerContentOptions={{
activeTintColor: '#fff', /* font color for active screen label */
activeBackgroundColor: '#68f', /* bg color for active screen */
inactiveTintColor: 'grey', /* Font color for inactive screens' labels */
}}
initialized by the following,
import * as React from 'react';
import {
Button,
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
} from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import {
createDrawerNavigator,
DrawerContentScrollView,
DrawerItem,
} from '#react-navigation/drawer';
import Home from '../home/containers';
import NavigationService from '../../navigation/NavigationService';
import * as homeActions from '../../features/home/actions';
import * as loginActions from '../../features/login/actions';
import { Images } from '../../config';
import i18n from 'i18n-js';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
onPress={() => NavigationService.navigate('Notifications')}
title="Go to notifications"
/>
</View>
);
}
function NotificationsScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button onPress={() => NavigationService.goBack()} title="Go back home" />
</View>
);
}
function CustomDrawerContent({ props, navigation }) {
const dispatch = useDispatch();
const outlets = useSelector((state) => state.homeReducer.outlets);
const defaultOutLet = useSelector((state) => state.homeReducer.defaultOutLet);
const drawerItems = outlets.map((outlet) => {
return (
console.log("############## nav drawr ################## " + outlet.name),
<DrawerItem
{...props}
key={outlet.userCompanyId}
label={outlet.name}
onPress={() => {
dispatch(homeActions.changeSelectedOutlet(outlet));
navigation.closeDrawer();
}}
/>
);
});
return (
<View style={styles.flexView}>
<View style={styles.container}>
<Image
style={styles.image}
source={Images.icons.logo}
resizeMode="contain"
/>
{defaultOutLet && <Text style={styles.text}>{defaultOutLet.name}</Text>}
</View>
<View style={styles.separator} />
<View style={styles.flexView}>{drawerItems}</View>
<View style={styles.separator} />
<View style={styles.bottomView}>
<TouchableOpacity
style={styles.logoutContainer}
onPress={() => {
dispatch(homeActions.clearUserCompany());
dispatch(loginActions.completeLogOutClearingUserData());
}}>
<Image
style={styles.logoutIcon}
source={Images.icons.power}
resizeMode="center"
/>
<Text style={styles.logoutText}>{i18n.t('common.logout')}</Text>
</TouchableOpacity>
</View>
</View>
);
}
const Drawer = createDrawerNavigator();
export default function DrawerNavigator() {
return (
<Drawer.Navigator
drawerContent={(props) => <CustomDrawerContent {...props} />}
initialRouteName="Home">
<Drawer.Screen name="Home" component={Home} />
</Drawer.Navigator>
);
}
const styles = StyleSheet.create({
container: {
flex: 0.3,
width: '100%',
backgroundColor: 'white',
},
flexView: {
flex: 1,
},
text: {
marginVertical: 12,
color: 'black',
textAlign: 'center',
},
logoutContainer: {
flexDirection: 'row',
alignItems: 'center',
width: '100%',
},
logoutText: {
color: 'gray',
},
logoutIcon: {
flex: 0.4,
},
image: {
flex: 1,
marginTop: 20,
alignSelf: 'center',
},
separator: {
width: '100%',
height: 1,
backgroundColor: 'gray',
},
bottomView: {
flex: 0.15,
width: '100%',
justifyContent: 'center',
},
});

React navigation hide drawer item

I am using React navigation 5.
I have a settings icon in the header that routes to the Setting Screen. So i want to hide the routes from the drawer.
Here's my code.
My CustomDrawerContent i have
const newState = { ...state };
newState.routes = newState.routes.filter((item) => item.name !== "Setting");
Its render function has:
<DrawerItemList state={newState} {...props} />
still the drawer item for settings has an empty container there. When i do console.log(newState.routes) it doesn't have setting.
Entire file is below
import React, { useContext } from "react";
import { View, StyleSheet } from "react-native";
import { connect } from "react-redux";
import {
Text,
Avatar,
ThemeContext,
Button,
Divider,
SocialIcon,
Icon,
} from "react-native-elements";
import {
DrawerContentScrollView,
DrawerItemList,
DrawerItem,
} from "#react-navigation/drawer";
import { signOut } from "../store/actions/authActions";
const CustomDrawerContent = (props) => {
const { theme } = useContext(ThemeContext);
const { state } = props;
const signOut = props.signOut;
const newState = { ...state };
newState.routes = newState.routes.filter((item) => item.name !== "Setting");
return (
<View style={{ flex: 1, backgroundColor: "#f5f5f5" }}>
<DrawerContentScrollView {...props}>
<View style={{ paddingVertical: 10, paddingHorizontal: 45 }}>
{/* View for profile pic area */}
<View
style={{
display: "flex",
flexDirection: "column",
marginTop: 25,
}}
>
<Avatar
size="large"
rounded={true}
icon={{ name: "rocket", color: "orange", type: "font-awesome" }}
overlayContainerStyle={{ backgroundColor: "white" }}
onPress={() => console.log("Works!")}
activeOpacity={0.7}
containerStyle={{ flex: 1 }}
/>
<Text
style={{
fontSize: 18,
fontWeight: "bold",
paddingTop: 10,
color: "#555",
}}
>
Olivia Groza
</Text>
<Text style={theme.Text.captionStyles}>#Govliva</Text>
<Button title="Go Pro" containerStyle={{ marginTop: 10 }}></Button>
</View>
</View>
<Divider
style={{ margin: 10, backgroundColor: "#dddddd", height: 1 }}
></Divider>
{console.log(newState.routes)}
<DrawerItemList state={newState} {...props} />
<DrawerItem
icon={({ color, size }) => (
<Icon name="home" type="material-community" color={color} />
)}
label="Logout"
onPress={signOut}
/>
</DrawerContentScrollView>
<View style={styles.shareContainer}>
<SocialIcon type="twitter" iconSize={18} style={styles.iconContainer} />
<SocialIcon
type="facebook"
iconSize={18}
style={styles.iconContainer}
/>
<SocialIcon
type="instagram"
iconSize={18}
style={styles.iconContainer}
/>
</View>
</View>
// <DrawerContentScrollView {...props}>
// <DrawerItemList {...props} />
// <Text>adfafsd</Text>
// </DrawerContentScrollView>
);
};
const styles = StyleSheet.create({
shareContainer: {
paddingHorizontal: 10,
display: "flex",
flexDirection: "row",
// justifyContent: "center"
},
iconContainer: {
height: 40,
width: 40,
},
});
const mapStateToProps = (state) => {
return {};
};
const mapDispathToProps = (dispatch) => {
return {
signOut: () => dispatch(signOut()),
};
};
export default connect(mapStateToProps, mapDispathToProps)(CustomDrawerContent);

How can I create a custom tabbar using React Navigation 5?

So, here is my tabbar:
I tried to use just a common navigation between screens when pressing the button, but that's not working in my situation. Also all of the methods I saw in google are deprecated. Is there a possibility to make a custom tabbar in React Navigation 5?
You should implement your custom tab bar, I created one as you have shown in the screenshot
Live Snack
import * as React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { MaterialCommunityIcons } from '#expo/vector-icons';
function HomeScreen() {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
}}>
<Text>Home!</Text>
</View>
);
}
function SettingsScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Settings!</Text>
</View>
);
}
function MyTabBar({ state, descriptors, navigation }) {
return (
<View
style={{
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
flexDirection: 'row',
backgroundColor: '#ccc',
height: 60,
borderTopRightRadius: 20,
borderTopLeftRadius: 20,
justifyContent: 'space-between',
alignItems: 'center',
}}>
{state.routes.map((route, index) => {
const { options } = descriptors[route.key];
const label =
options.tabBarLabel !== undefined
? options.tabBarLabel
: options.title !== undefined
? options.title
: route.name;
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
});
if (!isFocused && !event.defaultPrevented) {
navigation.navigate(route.name);
}
};
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',
target: route.key,
});
};
return (
<TouchableOpacity
accessibilityRole="button"
accessibilityStates={isFocused ? ['selected'] : []}
accessibilityLabel={options.tabBarAccessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
onLongPress={onLongPress}
style={{ flex: 1, justifyContent: 'space-between' }}>
{route.name === 'Home' ? (
<MaterialCommunityIcons
style={{ alignSelf: 'center' }}
name="home"
size={22}
color={isFocused ? '#673ab7' : '#222'}
/>
) : (
<MaterialCommunityIcons
style={{ alignSelf: 'center' }}
name="settings"
color={isFocused ? '#673ab7' : '#222'}
size={22}
/>
)}
<View
style={{
width: 8,
height: 3,
backgroundColor: isFocused ? '#00f' : '#777',
alignSelf: 'center',
}}
/>
</TouchableOpacity>
);
})}
</View>
);
}
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator
tabBarOptions={{
showIcon: true,
showLabel: false,
activeTintColor: 'red',
}}
tabBar={(props) => <MyTabBar {...props} />}>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Settings" component={SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}

how to make initialParams updated

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 .

Resources