How to add section divider in navigation drawer using react navigation - react-native

Suppose I have five items in drawer navigation. I want to add separator after three items. How to add this using react-navigation.

As mentioned vonovak, you could achieve this by using contentComponent which allows complete customization of drawer. For this you will need to create custom component which will override default drawer. Code sample:
Navigation Drawer
const NavigationDrawer = DrawerNavigator({
screen1: { screen: Screen1 },
screen2: { screen: Screen2 },
screen3: { screen: Screen3 },
}, {
contentComponent: SideMenu
})
Custom component which overrides default drawer (DrawerContainer)
class SideMenu extends React.Component {
render() {
return (
<View style={styles.container}>
<ScrollView>
<Text
onPress={() => this.props.navigation.navigate('Screen1')}
style={styles.item}>
Page1
</Text>
// 'separator' line
<View
style={{
borderBottomColor: 'black',
borderBottomWidth: 1
}}/>
<Text
onPress={() => this.props.navigation.navigate('Screen2')}
style={styles.item}>
Page2
</Text>
<Text
onPress={() => this.props.navigation.navigate('Screen3')}
style={styles.item}>
Page3
</Text>
</ScrollView>
</View>
);
}
}

You'll need to use the contentComponent prop to make custom changes. Check out the docs

If you are using DrawerItem component you can use itemStyle prop to add style as follows
const props = {
itemStyle: {
borderBottomWidth: 1,
borderColor: '#E2E4E8',
}
}
<DrawerItems {...props} />
You can also modify the style of container containing all items with
itemsContainerStyle prop.
Check official docs here.
3.x: https://reactnavigation.org/docs/3.x/drawer-navigator#contentoptions-for-draweritems
4.x: https://reactnavigation.org/docs/4.x/drawer-navigator#contentoptions-for-draweritems
5.x: DrawerContent is default drawer Item from v.5
You can pass props to it using drawerContentOptions object in Drawer.Navigator component.
https://reactnavigation.org/docs/5.x/drawer-navigator#drawercontentoptions
You can also pass custom drawer component using drawerContent prop.
https://reactnavigation.org/docs/5.x/drawer-navigator#drawercontent
6.x: Custom component can be added using drawerContent prop
https://reactnavigation.org/docs/drawer-navigator#drawercontent
Style to drawerItem is changed to
https://reactnavigation.org/docs/drawer-navigator#draweritemstyle

Just add this code:
const Seperator = () => <View style={styles.separator} />;
at the top of your code that you want to have the section divider/separator on. If it's a navigation drawer, menu, categories or etc.
Add this styling prop:
separator: {
marginVertical: 8,
borderBottomColor: "#737373",
borderBottomWidth: StyleSheet.hairlineWidth
}
Add section divider/separator between each section, menu, category block of code that you want to separate them like this:
//Block of code of first section/menu/category starts from here
<Icon.Button
name="th-large"
raised={true}
backgroundColor="#ffa500"
size={30}
onPress={() => {
Linking.openURL("https://www.buymeacoffee.com/splendor");
}}
>
<Text style={{ fontSize: 15 }}>
Herat: The "Academy" of Prince Bay Sunghur (1420-1433)
</Text>
</Icon.Button>
**<Seperator />**
//Block of code of first section/menu/category ends here
//Block of code of second section/menu/category starts from here
<Icon.Button
name="th-large"
raised={true}
backgroundColor="#ffa500"
size={30}
onPress={() => {
Linking.openURL("https://www.buymeacoffee.com/splendor");
}}
>
<Text style={{ fontSize: 15 }}>
Venice, Istanbul, and Herat (15th Century)
</Text>
</Icon.Button>
**<Seperator />**
//Block of code of second section/menu/category ends here
//Block of code of third section/menu/category starts from here
<Icon.Button
name="th-large"
raised={true}
backgroundColor="#ffa500"
size={30}
onPress={() => {
Linking.openURL("https://www.buymeacoffee.com/splendor");
}}
>
<Text style={{ fontSize: 15 }}>
The Age of Bihzad of Herat (1465-1535)
</Text>
</Icon.Button>
**<Seperator />**
//Block of code of thirds section/menu/category ends here

Related

Navigating to cart screen with stack navigation header

I am having a stack navigator that consists of 7 different screens and a cart icon is placed on the every screen header. I want to navigate by pressing that cart icon to the cart screen/page. I tried to put onPress function on the icon and in the header option also but all in vain.
Also, I want to know how the cart system will work.
Below is my single stack navigator screen
<HomeStack.Screen name="EARRINGS" component={Earring}
options={{headerRight:() => <ShoppingCartIcon /> }}
/>
Below is my ShoppingCartIcon code:
const ShoppingCartIcon = () => {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<View style={{position: 'absolute', top: -20, right: 0, width: 70, height: 70, alignItems:"center",justifyContent:"center", zIndex:2000 }}>
<Text style={{fontSize:20,fontWeight:"bold"}}>0</Text>
</View>
<AntDesign name="shoppingcart" color="black" size={24} style={{marginRight:10}} />
</View>
)
}
export default (ShoppingCartIcon)
Please help me.
You can pass the navigation prop like below
<HomeStack.Screen
name="EARRINGS"
component={Earring}
options={({ navigation }) => ({
headerRight: () => (<ShoppingCartIcon navigation={navigation}/> )
})}
/>
And you can use the navigation prop to navigate to any screen you need
const ShoppingCartIcon = ({navigation}) => {
//other code
navigation.navigate('Cartscreen')
}

How can I use tabs in a modal in react-native

I have modal for filtering search resluts , something like foursquare app . I have filters in diffrent categories and I need to use tabs for each category . for example when user clicks each tabs it shows the filters related to that tab . and user can select checkboxes or radio buttons . and at the end when user checks all of their needed filters I need to make http request with the new filters.
Something like the image below . I created the modal but I need the functionality for tabs and at the end making the api request with the selected options:
You can also create custom tabs using <Text> with state and depending on a state value render a View associated with that tab. for example
state = {
modalVisible: false,
currentTab: 1,
};
onTabClick = (currentTab) => {
this.setState({
currentTab: currentTab,
});
};
// inside render
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={styles.tabs}>
<Text
onPress={() => {
this.onTabClick(1);
}}
style={[
styles.tabTextStyle,
this.state.currentTab === 1 ? styles.tabUnderline : null,
]}>
GENDER
</Text>
...
</View>
{this.state.currentTab === 1 && (
<View>
<Text>GENDER</Text>
</View>
)}
...
snack example
Modal is just a Container like View. You can draw anything inside it.
First, import {Modal} from 'react-native'
Then, in your modal, embed anything what you want:
<Modal visible={ this.state.modal }
animationType="fade" transparent={true}
onRequestClose={_ => this.setState({ modal: false }) }>
<View>
{/*
Do anything. Its an open ground.
Whatever component, styles, props and/or anything else you want, you can design
*/}
{/* For example, I am adding a close button */}
<TouchableOpacity style={{ alignSelf: 'flex-end' }} onPress={_ => this.setState({ modal: false }) }>
<Icon type="FontAwesome" name='times' style={ styles.closeIcon } />
</TouchableOpacity>
</View>
</Modal>
And you can open your modal from anywhere like:
<TouchableOpacity style={ styles.button } onPress={_ => this.setState({ modal: true }) }>
<Text style={ styles.buttonText }>Open Modal</Text>
</TouchableOpacity>
Finally, for tabs, you can use either of:
NativeBase Tab Component
React Native Tab View

How to set the textinput box above the Keyboard while entering the input field in react native

I am using react-native TextInput component. Here I need to show the InputBox above the keyboard if the user clicks on the textInput field.
I have tried below but i am facing the issues
1. Keyboard avoiding view
a. Here it shows some empty space below the input box
b. Manually I need to scroll up the screen to see the input field which I was given in the text field
c. Input box section is hiding while placing the mouse inside the input box
2. react-native-Keyboard-aware-scroll-view
a.It shows some empty space below the input box
b.ScrollView is reset to the top of the page after I moving to the next input box
Here I set the Keyboard-aware-scroll-view inside the ScrollView component
Kindly clarify
My example code is
<SafeAreaView>
<KeyboardAvoidingView>
<ScrollView>
<Text>Name</Text>
<AutoTags
//required
suggestions={this.state.suggestedName}
handleAddition={this.handleAddition}
handleDelete={this.handleDelete}
multiline={true}
placeholder="TYPE IN"
blurOnSubmit={true}
style= {styles.style}
/>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
[https://github.com/APSL/react-native-keyboard-aware-scroll-view]
Give your TextInput a position: absolute styling and change its position using the height returned by the keyboardDidShow and keyboardDidHide events.
Here is a modification of the Keyboard example from the React Native documentation for demonstration:
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
state = {
keyboardOffset: 0,
};
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this._keyboardDidShow,
);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this._keyboardDidHide,
);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow(event) {
this.setState({
keyboardOffset: event.endCoordinates.height,
})
}
_keyboardDidHide() {
this.setState({
keyboardOffset: 0,
})
}
render() {
return <View style={{flex: 1}}>
<TextInput
style={{
position: 'absolute',
width: '100%',
bottom: this.state.keyboardOffset,
}}
onSubmitEditing={Keyboard.dismiss}
/>
</View>;
}
}
First of all, You don't need any extra code for Android platform. Only keep your inputs inside a ScrollView. Just use KeyboardAvoidingView to encapsulate the ScrollView for iOS platform.
Create function such as below which holds all the inputs
renderInputs = () => {
return (<ScrollView
showsVerticalScrollIndicator={false}
style={{
flex: 1,
}}
contentContainerStyle={{
flexGrow: 1,
}}>
<Text>Enter Email</Text>
<TextInput
style={styles.text}
underlineColorAndroid="transparent"
/>
</ScrollView>)
}
Then render them inside the main view as below
{Platform.OS === 'android' ? (
this.renderInputs()
) : (
<KeyboardAvoidingView behavior="padding">
{this.renderInputs()}
</KeyboardAvoidingView>
)}
I have used this method and I can assure that it works.
If it is not working then there is a chance that you are missing something.
Hooks version:
const [keyboardOffset, setKeyboardOffset] = useState(0);
const onKeyboardShow = event => setKeyboardOffset(event.endCoordinates.height);
const onKeyboardHide = () => setKeyboardOffset(0);
const keyboardDidShowListener = useRef();
const keyboardDidHideListener = useRef();
useEffect(() => {
keyboardDidShowListener.current = Keyboard.addListener('keyboardWillShow', onKeyboardShow);
keyboardDidHideListener.current = Keyboard.addListener('keyboardWillHide', onKeyboardHide);
return () => {
keyboardDidShowListener.current.remove();
keyboardDidHideListener.current.remove();
};
}, []);
You can use a scrollview and put all components inside the scrollview and add automaticallyAdjustKeyboardInsets property to scrollview.it will solve your problem.
automaticallyAdjustKeyboardInsets Controls whether the ScrollView should automatically adjust its contentInset and
scrollViewInsets when the Keyboard changes its size. The default value is false.
<ScrollView automaticallyAdjustKeyboardInsets={true}>
{allChildComponentsHere}
<View style={{ height: 30 }} />//added some extra space to last element
</ScrollView>
Hope it helps.
you can use KeyboardAvoidingView as follows
if (Platform.OS === 'ios') {
return <KeyboardAvoidingView behavior="padding">
{this.renderChatInputSection()}
</KeyboardAvoidingView>
} else {
return this.renderChatInputSection()
}
Where this.renderChatInputSection() will return the view like textinput for typing message. Hope this will help you.
For android you can set android:windowSoftInputMode="adjustResize" for Activity in AndroidManifest file, thus when the keyboard shows, your screen will resize and if you put the TextInput at the bottom of your screen, it will be keep above keyboard
react-native-keyboard-aware-scroll-view caused similar issue in ios. That's when I came across react-native-keyboard-aware-view. Snippets are pretty much same.
<KeyboardAwareView animated={true}>
<View style={{flex: 1}}>
<ScrollView style={{flex: 1}}>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>A</Text>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>B</Text>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>C</Text>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>D</Text>
</ScrollView>
</View>
<TouchableOpacity style={{height: 50, backgroundColor: 'transparent', alignItems: 'center', justifyContent: 'center', alignSelf: 'stretch'}}>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>Submit</Text>
</TouchableOpacity>
</KeyboardAwareView>
Hope it hepls
You will definitely find this useful from
Keyboard aware scroll view Android issue
I really don't know why you have to add
"androidStatusBar": {
"backgroundColor": "#000000"
}
for KeyboardawareScrollview to work
Note:don't forget to restart the project without the last step it might not work
enjoy!
I faced the same problem when I was working on my side project, and I solved it after tweaking KeyboardAvoidingView somewhat.
I published my solution to npm, please give it a try and give me a feedback! Demo on iOS
Example Snippet
import React from 'react';
import { StyleSheet, TextInput } from 'react-native';
import KeyboardStickyView from 'rn-keyboard-sticky-view';
const KeyboardInput = (props) => {
const [value, setValue] = React.useState('');
return (
<KeyboardStickyView style={styles.keyboardView}>
<TextInput
value={value}
onChangeText={setValue}
onSubmitEditing={() => alert(value)}
placeholder="Write something..."
style={styles.input}
/>
</KeyboardStickyView>
);
}
const styles = StyleSheet.create({
keyboardView: { ... },
input: { ... }
});
export default KeyboardInput;
I based my solution of #basbase solution.
My issue with his solution that it makes the TextInput jumps up without any regard for my overall view.
That wasn't what I wanted in my case, so I did as he suggested but with a small modification
Just give the parent View styling like this:
<View
style={{
flex: 1,
bottom: keyboardOffset,
}}>
And it would work! the only issue is that if the keyboard is open and you scrolled down you would see the extra blank padding at the end of the screen.
android:launchMode="singleTask"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
write these two lines in your android/app/src/main/AndroidManifest.xml
in activity tag
flexGrow: 1 is the key.
Use it like below:
<ScrollView contentContainerStyle={styles.container}>
<TextInput
label="Note"
value={currentContact.note}
onChangeText={(text) => setAttribute("note", text)}
/>
</ScrollView>
const styles = StyleSheet.create({
container: {
flexGrow: 1,
},
});
Best and Easy Way is to use Scroll View , It will Automatically take content Up and TextInput will not be hide,Can refer Below Code
<ScrollView style={styles.container}>
<View>
<View style={styles.commonView}>
<Image source={firstNameIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>First Name</Text>
</View>
<TextInput
onFocus={() => onFocus('firstName')}
placeholder="First Name"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'firstName')}
value={firstNameValue}
/>
</View>
<View>
<View style={styles.commonView}>
<Image source={LastNameIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>Last Name</Text>
</View>
<TextInput
onFocus={() => onFocus('lastName')}
placeholder="Last Name"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'lastName')}
value={lastNameValue}
/>
</View>
<View>
<View style={styles.commonView}>
<Image source={callIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>Number</Text>
</View>
<TextInput
onFocus={() => onFocus('number')}
placeholder="Number"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'number')}
value={numberValue}
/>
</View>
<View>
<View style={styles.commonView}>
<Image source={emailIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>Email</Text>
</View>
<TextInput
onFocus={() => onFocus('email')}
placeholder="Email"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'email')}
value={emailValue}
/>
</View>
<View style={styles.viewSavebtn}>
<TouchableOpacity style={styles.btn}>
<Text style={styles.saveTxt}>Save</Text>
</TouchableOpacity>
</View>
</ScrollView>
go to your Android>app>src>main> AndroidManifest.xml
write these 2 lines :
android:launchMode="singleTop" android:windowSoftInputMode="adjustPan"

Define right button of NavBar in component, not in Scene (react-native-router-flux)

I'm using react-native-router-flux for navigation in my app.
I want to define right button of NavBar in component, not in Scene, how should I do this?
Here is the code of the Scene:
<Scene
navBar={PlatformNavbar}
leftElement={ <Text style={{color: Colors.white, marginLeft: 25, fontWeight:'500' }}>Go Back</Text> }
key='nodScreen'
component={NodScreen}
hideNavBar={false}
/>
I'm using my custom navBar, I have functions for rendering right and left element: leftElement, rightElement.
In order to render right element in the component, I was using this code, however, it didn't render anything.
componentDidMount() {
Actions.refresh({rightElement: this.renderRightElement
}) }
renderRightElement = () => {
return ( <TouchableOpacity onPress={() => {} }>
<Image style={{height: 24, width: 24, marginRight: 16}} source={{uri: 'score_progress_empty'}} resizeMode='contain'/>
</TouchableOpacity>)
}
Have you tried using right instead of rightElement
componentDidMount() {
Actions.refresh({
right : this.renderRightElement,
})
}
Check out this issue on RNRF page for more details

React-native-popup-menu on react-navigation header

I'm using redux with react-navigation and would like to show the popup when the user clicks on the button on the react-navigation header-right button.
I wrapped the context menu at the root of my apps, as below
return (
<Provider store={store}>
<MenuContext style={{ flex: 1 }}>
<AppWithNavigationState />
</MenuContext>
</Provider>
)
in one of my screen, I have
static navigationOptions = {
headerTitle: 'News',
headerRight: (
<TouchableOpacity style={{ paddingLeft:15, paddingRight:15 }}>
<Icon name="more-vert" size={30} color="black" />
</TouchableOpacity>
),
}
When the user clicks on the right button, it should be like this
The menu items are dynamic, I will have to pull the data from one of my API and start rendering the menu data.
I've read through online it can be achieved using the context method, but I'm not sure how to implement it in my structure.
Could anyone advise me on this?
And is it possible to render it with my local variable?
The most custom way is to use Modal, when click the right button, called this.refs.modalRef.showModal(), which in your current page:
<View>
<PopupModal ref="modalRef" />
</View>
The PopupModal like this:
export default class PopupModal extends Component {
state = {
show: false,
}
showModal() {
this.setState({show: true});
}
closeModal = () => {
this.setState({show: false});
}
return (
<Modal
transparent
visible={this.state.show}
onRequestClose={this.closeModal}
>
<TouchableWithoutFeedback onPress={this.closeModal}>
<View style={{
width: '100%',
height: '100%',
opacity: 0.5,
backgroundColor: 'gray',
}} />
</TouchableWithoutFeedback>
<View></View> // your designed view, mostly position: 'absolute'
</Modal>
);
}
You can also pass some data to PopupModal by this.refs.modalRef.showModal(data), and in PopupModal:
showModal = (data) => {
this.setState({ data, show: true });
}
https://www.npmjs.com/package/react-native-material-menu
It works to me
headerRight:<View style={{marginRight:10}}>
<Menu
ref={this.setMenuRef}
button={<Text onPress={this.showMenu}><Icon style={{color:screenProps.headerTitleStyle.color,fontSize:25,marginRight:5}} name="md-more"/></Text>}
>
<MenuItem onPress={this.hideMenu}>Rate Us</MenuItem>
<MenuItem onPress={this.hideMenu}>Share App</MenuItem>
<MenuItem onPress={this.hideMenu}>Settings</MenuItem>
</Menu>
</View>,