Search code examples
reactjsreact-native-picker

Render Picker Items from React-Native picker to populate drop-menu selections


I am successfully using the react-native picker to render a drop-menu in one of my components. Right now, in the picker code I am hardcoding the values used to populate the drop-menu items. What I'd ideally like to do is pass these in as props, and have them dynamically generate as many items as necessary within the picker. I'm not sure how to do that, though. I tried using a for-loop but I can't run that kind of conditional logic within the component code itself. This is what it looks like with hard coded values.

export const DropDownMenu = (props) => {
  const [selectedValue, setSelectedValue] = useState(null);
  return (
    <View style={styles.container}>
      <Picker
        selectedValue={selectedValue}
        style={{ height: 50, width: 150 }}
        onValueChange={(itemValue, itemIndex) => {
          props.onSelectMenuValue(itemValue), 
          setSelectedValue(itemValue)
        }}
      >
        <Picker.Item label="A" value="a" />
        <Picker.Item label="B" value="b" />
        <Picker.Item label="C" value="c" />
      </Picker>
    </View>
  );
}

How could I render Picker.Item values based on the props passed in?


Solution

  • You can pass an options prop as an array of objects with a label and a value property and use map like this:

    <Picker /*whatever you need for picker here*/>
    {props.options.map(option => <Picker.Item label={option.label} value={option.value}/>)}
    </Picker>