Skip to content

Instantly share code, notes, and snippets.

@thargenediad
Created March 24, 2020 04:07
Show Gist options
  • Save thargenediad/7615e281baab25733ca0e7f5c7cb97d6 to your computer and use it in GitHub Desktop.
Save thargenediad/7615e281baab25733ca0e7f5c7cb97d6 to your computer and use it in GitHub Desktop.
PickerDropDown class for React Native (fixes Picker issues on iOS) - modified version of the one written by @kevin and shared to StackOverflow: https://stackoverflow.com/users/4135310/kevin
import React from 'react';
import { View, Picker, ActionSheetIOS, Platform, StyleSheet } from 'react-native';
import { Button, Icon } from 'react-native-elements';
export default class PickerDropDown extends React.Component {
onIOSButton = () => {
let options = this.props.children.map((item, i) => {
return item.props.label;
});
options.push("Cancel");
ActionSheetIOS.showActionSheetWithOptions(
{
options: options,
cancelButtonIndex: options.length - 1,
},
this.onIOSButtonPick
);
}
onIOSButtonPick = (buttonIndex) => {
if (buttonIndex < this.props.children.length && buttonIndex != this.props.selectedValue) {
if (typeof this.props.selectedValue === 'undefined' || (typeof this.props.selectedValue !== 'undefined' && buttonIndex != this.findIndexForValue(this.props.selectedValue))) {
this.props.onValueChange(this.props.children[buttonIndex].props.value, buttonIndex);
}
}
}
findLabelForValue = (searchValue) => {
for (let i = 0; i < this.props.children.length; i++) {
if (this.props.children[i].props.value == searchValue) {
return this.props.children[i].props.label;
}
}
return null;
}
findIndexForValue = (searchValue) => {
for (let i = 0; i < this.props.children.length; i++) {
if (this.props.children[i].props.value == searchValue) {
return i;
}
}
return -1;
}
render() {
if (Platform.OS === "ios") {
let title = "";
if (this.props.children && this.props.children.length > 0) {
if (typeof this.props.selectedValue !== 'undefined') {
title = this.findLabelForValue(this.props.selectedValue);
} else {
title = this.props.children[0].props.label;
}
}
return (
<View style={ styles.dropdownContainer }>
<View style={ styles.dropdownButtonContainer }>
<Button
textStyle={{ color: 'black' }}
title={title}
onPress={this.onIOSButton}
type="clear"
fontSize={15}
transparent
/>
</View>
<View style={ styles.dropdownIconContainer }>
<Icon
name="arrow-drop-down"
size={20}
color="black"
iconStyle={ styles.dropdownIcon }
/>
</View>
</View>
);
} else {
return (
<Picker {...this.props} />
);
}
}
}
const styles = StyleSheet.create({
dropdownContainer: {
flexDirection: 'row',
width: '100%',
flex: 1,
alignSelf: 'stretch'
},
dropdownButtonContainer: {
width: '100%',
justifyContent: 'center',
marginRight: 0
},
dropdownIconContainer: {
justifyContent: 'center'
},
dropdownIcon: {
marginLeft: -50
}
});
@DEVfancybear
Copy link

not run android, help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment