Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native: trigger onPress event (Picker component)

Tags:

react-native

For some reason, the same Picker component behaves as list of options on iOS and as button on Android. I have no idea, who decided, that this is good idea to put it like that.

I want to hide <Picker/> on android and render TouchableOpacity instead. It solves styling problems. However, i don't know, how do I make TouchableOpacity onPress method to trigger onPress event for the hidden <Picker />?

like image 296
stkvtflw Avatar asked Sep 27 '16 05:09

stkvtflw


1 Answers

React Native's Picker component (which has now been moved to @react-native-community/react-native-picker) is not a custom component but instead uses the platform specific native picker component, just like the Alert API.

To get what youre trying to achieve -

import { TouchableOpacity, Platform } from "react-native"
import { Picker } from '@react-native-community/picker';

then in your render method check the Platform and render appropriate elements

iosPicker = () => (
  <Picker
  selectedValue={this.state.language}
  style={{height: 50, width: 100}}
  onValueChange={(itemValue, itemIndex) =>
    this.setState({language: itemValue})
  }>
    <Picker.Item label="Java" value="java" />
    <Picker.Item label="JavaScript" value="js" />
  </Picker>
)

androidPicker = () => (
  <View>
    <TouchableOpacity
      onPress={() => this.setState({language: "java"})
    >
      <Text>Java</Text>
    </TouchableOpacity>
    <TouchableOpacity
      onPress={() => this.setState({language: "js"})
    >
      <Text>JavaScript</Text>
    </TouchableOpacity>
  </View>
)



render() {
  return(
  <View>
    { Platform.OS === "ios" ? this.iosPicker() : this.androidPicker() }
  </View>
  )

for those of you looking for simpler third party plug and play solutions here are a few options:

  • react-native-modal-picker

  • react-native-actionsheet

like image 89
Karan Wadhwa Avatar answered Nov 12 '22 14:11

Karan Wadhwa