React Native using React Navigation - Show/Hide Drawer Item
I was wondering if you guys or maybe someone have come up of a better Idea of showing or hiding some menu or Drawer Item under DrawerNavigator.
Basically I have user roles and I want to show/hide selected menu's based on user's role.
My setup now is that I have A DrawerNavigator nested within a StackNavigator.
Menu That Contains My Drawer Items
Hide some drawer items based on user role
Currently Using:
react version 16.0.0-alpha.12
react-native version 0.46.0
react-navigation version 1.0.0-beta.11
You can create your own custom component that will be rendering drawer items
contentComponent: CustomDrawerContentComponent
inside that component you can define logic on show hide your items
example:
const CustomItems = ({
navigation: { state, navigate },
items,
activeItemKey,
activeTintColor,
activeBackgroundColor,
inactiveTintColor,
inactiveBackgroundColor,
getLabel,
renderIcon,
onItemPress,
style,
labelStyle,
}: Props) => (
<View style={[styles.container, style]}>
{items.map((route: NavigationRoute, index: number) => {
const focused = activeItemKey === route.key;
const color = focused ? activeTintColor : inactiveTintColor;
const backgroundColor = focused
? activeBackgroundColor
: inactiveBackgroundColor;
const scene = { route, index, focused, tintColor: color };
const icon = renderIcon(scene);
const label = getLabel(scene);
return (
<TouchableOpacity
key={route.key}
onPress={() => {
console.log('pressed')
onItemPress({ route, focused });
}}
delayPressIn={0}
>
<View style={[styles.item, { backgroundColor }]}>
{icon ? (
<View style={[styles.icon, focused ? null : styles.inactiveIcon]}>
{icon}
</View>
) : null}
{typeof label === 'string' ? (
<Text style={[styles.label, { color }, labelStyle]}>{label}</Text>
) : (
label
)}
</View>
</TouchableOpacity>
);
})}
</View>
);
So in the code above you can define which route will be shown, for instance you can have store with list of items show or hide and from here you can make comparison.
Hope it helps
Related
Nested TextInput component does not allow other components' onPress function to be called. Only when the TextInput is not focused, the onPress works fine.
React Native Version : 0.66.3
Here is my code
export const Component = (props): JSX.Element {
const { searchText, onChangeSearchText, onClearSearchText } = props
const [searchViewFocused, setSearchViewFocused] = useState<boolean>(false)
const searchIcon = searchViewFocused ? "searchActive" : "searchInactive"
const cancelIcon = searchViewFocused ? "cancelActive" : "cancelInactive"
return (
<View style={styles.searchBoxContainer}>
<View style={[styles.searchBox, searchViewFocused && styles.searchBarActive]}>
<Icon styles={styles.searchIcon} icon={searchIcon} />
<TextInput
style={styles.searchInput}
onChangeText={onChangeSearchText}
value={searchText}
onFocus={() => setSearchViewFocused(true)}
onBlur={() => setSearchViewFocused(false)}
autoCompleteType={"off"}
numberOfLines={1}
/>
{searchText !== "" && (
<Pressable style={styles.clearIcon} onPress={onClearSearchText}>
<Icon icon={cancelIcon} />
</Pressable>
)}
</View>
</View>
)
})
Attached are the images of
Expected.
VS
The issue
When the cross icon is pressed on focused state, the textInput is unfocused rather What I am trying to achieve is that the search text gets cleared & the input remains focused.
Note: The onPress works perfectly fine when input is not focused
Any help is appreciated. Thanks!
PS: Tried TouchableOpacity & also I have tried wrapping the components inside a ScrollView to use keyboardShouldPersistTaps='handled' as mentioned in one of the SO answer but to no success.
Found a workaround to this is to wrap the whole component into a ScrollView and adding the prop keyboardShouldPersistTaps='handled'
Previously I was making the View inside the Component as ScrollView and adding keyboardShouldPersistTaps='handled' which did not work
export const Component = (props): JSX.Element {
...
return (
<ScrollView contentContainerStyle={styles.searchBoxContainer}
keyboardShouldPersistTaps='handled'>
...
</ScrollView>
)
})
The key was to wrap the entire component inside the ScrollView,
Here's what worked:
<ScrollView keyboardShouldPersistTaps='handled'>
<Component {...props}/>
</ScrollView>
Guess this was a silly mistake, but worth pointing out!
You're setting the focus of the entire component based on whether the TextInput has focus. Since the clear button is outside the text input, pressing it causes the component to lose focus.
One solution is to store the TextInput instance in a ref. When the clear button is pressed, you can refocus the text input. I've copied your component below and added some new lines, which are marked in comments.
export const Component = (props): JSX.Element {
const { searchText, onChangeSearchText, onClearSearchText } = props
const textInputRef = useRef(null); // new
const [searchViewFocused, setSearchViewFocused] = useState<boolean>(false)
const searchIcon = searchViewFocused ? "searchActive" : "searchInactive"
const cancelIcon = searchViewFocused ? "cancelActive" : "cancelInactive"
const onClear = () => {
onClearSearchText();
textInputRef.current?.focus();
} // new
return (
<View style={styles.searchBoxContainer}>
<View style={[styles.searchBox, searchViewFocused && styles.searchBarActive]}>
<Icon styles={styles.searchIcon} icon={searchIcon} />
<TextInput
ref={textInputRef} // new
style={styles.searchInput}
onChangeText={onChangeSearchText}
value={searchText}
onFocus={() => setSearchViewFocused(true)}
onBlur={() => setSearchViewFocused(false)}
autoCompleteType={"off"}
numberOfLines={1}
/>
{searchText !== "" && (
<Pressable style={styles.clearIcon} onPress={onClear}> // calls new function
<Icon icon={cancelIcon} />
</Pressable>
)}
</View>
</View>
)
})
I'm just starting at React native and i want to update the state from my home page with a click on a custom button.
I made this code juste bellow. When I click on my buttons, i can't see the state change.
const Home = () => {
const welcomeSentence =
"Bonjour, est ce que tu as fais ton workout aujourd'hui ?";
const [isWorkoutDone, setIsWorkoutDone] = useState(false);
return (
<View style={styles.container}>
<Text style={styles.homePageText}>{welcomeSentence}</Text>
<View style={styles.buttonContainer}>
<AppButton title ="OUI" onPress={()=>this.setIsWorkoutDone(true)}/>
<AppButton title ="NON" onPress={()=>this.setIsWorkoutDone(false)}/>
</View>
<Text>{isWorkoutDone ? "OK" : "KO"}</Text>
</View>
);
};
With this code on my cutom button :
const AppButton = (props) => {
return (
<Button
title={props.title}
onPress={props.onPress}
style={styles.appButton}
/>
);
};
I tested and make search but I didn't find why my state didn't change.
You are using functional component so you don't need this.
<AppButton title ="OUI" onPress={()=>setIsWorkoutDone(true)}/>
<AppButton title ="NON" onPress={()=>setIsWorkoutDone(false)}/>
Hi I am using React navigation v5.
I am trying to implement custom header for specific screen. So my custom header looks like this
CustomHeader.js
export function CustomHeader({props}) {
const {scene, previous, navigation} = props;
const opacity = scene.route.params.opacity;
return (
<React.Fragment>
<Animated.View style={[styles.headerStyle, {opacity}]}>
<View style={styles.influencerNameContainer}>
<Text style={styles.influencerName}>
{scene.route.params.influencer.user.name}
</Text>
</View>
</Animated.View>
{previous ? (
/* This is a back button */
<Button
style={[styles.iconButton, {left: 0}]}
icon={BackIcon}
onPress={() => {navigation.goBack}
/>
) : (
undefined
)}
</React.Fragment>
);
}
Navigator looks like this
export function HomeStack() {
return (
<Stack.Navigator
initialRouteName="Home"
headerMode="screen"
style={{backgroundColor: 'yellow'}}>
<Stack.Screen
name="InfluencerScreen"
component={InfluencerScreen}
options={{
header: props => <CustomHeader props={props} />,
}}
/>
</Stack.Navigator>
);
}
It renders custom headers and custom back button but back button is not clickable.
So I tried.
<Stack.Screen
name="InfluencerScreen"
component={InfluencerScreen}
options={{
header: props => <CustomHeader props={props} />,
headerLeft: () => (
<Button title="Back Button" onPress={() => alert('Pressed')} />
)
}}
/>
With this code, it doesn't show back button at all with custom header. But it shows custom back button when I remove custom header(header: props => ).
What am I missing?
You're showing a custom header, how you render the button is up-to you. React Navigation cannot show a back button since React Navigation is no longer rendering the header.
Instead of using headerLeft option, you need to put the back button inside your custom header.
Also your destructuring is incorrect. function CustomHeader({props}) should be function CustomHeader(props) (without the curly braces).
You're destructuring props twice.. Try:
export function CustomHeader({scene, previous, navigation}) {
// const {scene, previous, navigation} = props; // remove this
...
}
Edit:
Also goBack is a method so call it with parentheses:
onPress={() => navigation.goBack()} // remove unnecessary `curly braces`
I am using redux to track which screen user is at.
I have a button tab component:
Tab.js:
class Tab extends Component {
render() {
return (
<Button onPress={() => navigation.navigate(route)}>
<Icon
style={selected ? deviceStyle.tabSelectedColor : deviceStyle.tabDefaultColor}
type="Ionicons"
name={icon}
/>
<Text style={selected ? deviceStyle.tabSelectedColor : deviceStyle.tabDefaultColor}>
{title}
</Text>
</Button>
);
}
}
Then I call it from another component:
const items = [
{
screen: 'home',
title: 'home',
icon: 'apps',
route: 'Home'
}]
renderTab = () => {
return items.map((tabBarItem, index) => {
return (
<Tab
key={index}
title={tabBarItem.title}
icon={tabBarItem.icon}
route={tabBarItem.route}
/>
);
});
};
Now, when user change screen, how can I change the selected props in tab component?
There are two ways to achieve this.
1) Onclick / onpress of your Tab you can dispatch an action, which will update user's current screen, as currently, you are navigating user on that page.
2) On load of screen, which is going to load after tab click/press.
You just need an action which will update user's current screen
I am new to react native.
My question is pretty simple: my screen contains 5 buttons. Each one opens the same < Modal > component. I need to dynamically change the content of the modal, depending on the button clicked.
For example:
if I click the first button, a text input will be shown into the modal.
If I click the second button, checkboxes will be shown into the modal.
Here's my modal :
<Modal
visible={this.state.modalVisible}
animationType={'slide'}
onRequestClose={() => this.closeModal()}>
<View style={style.modalContainer}>
<View style={style.innerContainer}>
<Text>This is content inside of modal component</Text>
<Button
onPress={() => this.closeModal()}
title="Close modal"
>
</Button>
</View>
</View>
</Modal>
Here I open it :
openModal() {
this.setState({ modalVisible: true });
}
Here I call the function (on button press) :
onPress={() => this.openModal()}
I've heard about using props/children, but I don't know how to use them is this case.
Can anyone please help ?
Here is quick example to show who to render different content based on input you provide.
Modal Content
renderModalContent(type, data) {
switch(type) {
1: {
return (
<View>{..data}</View>
)
}
2: {
return (
<Button>...</Button>
)
}
default: (<CustomComponent data={data} />)
}
}
Modal
<Modal>
<View>
{this.renderModalContent(this.state.type, this.state.modalContentData)}
</View>
</Modal>
Here you decide which view you want to render and pass its data.
openModal() {
this.setState({ modalVisible: true, type: 1, data: {...} });
}
You should modify your Modal component so that it renders the base layout with space for dynamic content to be rendered. The content will be passed in as children, via Props. This will mean the modal is dynamic and will / should support future requirements. Try to avoid the switch case in the modal render suggestion unless you have very specific requirements that are unlikely to change in the future, or if you want to do things the React way.
Then for each variant of your Modal (TextInput, Checkbox etc.) create a new Component that wraps the Modal component and have each button initiate rendering the specific component.
If you're using Redux then you would be creating containers, connecting to Redux and passing dynamic state variables. You don't have to use Redux but the principle is the same.
Here's a very basic example to illustrate my point.
// Basic modal that renders dynamic content
const Modal = props => {
const { children } = props;
render (
<View style={styles.modal} >
{children}
</View>
);
}
// Specific modal implementation with TextInput
const ModalWithTextInput = props => (
<Modal>
<TextInput
value={props.someValue}
/>
</Modal>
)
// Specific modal implementation with Switch
const ModalWithSwitch = props => (
<Modal>
<Switch
value={props.someValue}
/>
</Modal>
)
Then in your component that launches the modals, do something like this...
class MyComponent extends Component {
openTextModal = () => {
this.setState({ modalType: 'text' });
}
openSwitchModal = () => {
this.setState({ modalType: 'switch' });
}
renderModal = (type) => {
if (type === 'text') {
return(<ModalWithTextInput />)
}
if (type === 'switch') {
return(<ModalWithSwitch />)
}
}
render() {
const { modalType } = this.state;
render (
<View>
<View>
<TouchableWithX onPress={this.openTextModal} />
<TouchableWithX onPress={this.openSwitchModal} />
</View>
<View>
{this.renderModal(modalType)}
</View>
</View>
);
}
}
Please note this code has not tested but the principle is sound.