Search code examples
arraysreact-nativemulti-select

react-native-multiple-select storing items selected on submit


I am using react-native-multiple-select and trying to create a dropdown menu that allows users to select multiple options and then logs the options they select into an array. At the moment, my code is:

    onSelectedItemsChange = selectedItems => {
    this.setState({ selectedItems });
    console.log('submit button was pressed')
  };

  render() {
    const { selectedItems } = this.state;
    return (
      <View style={{ flex: 1 }}>
        <MultiSelect
          hideTags
          items={items}
          uniqueKey="id"
          ref={(component) => { this.multiSelect = component }}
          onSelectedItemsChange={this.onSelectedItemsChange}
          selectedItems={selectedItems}
          selectText="Pick Items"
          searchInputPlaceholderText="Search Items..."
          onChangeInput={ (text)=> console.log(text)}
          altFontFamily="ProximaNova-Light"
          tagRemoveIconColor="#CCC"
          tagBorderColor="#CCC"
          tagTextColor="#CCC"
          selectedItemTextColor="#CCC"
          selectedItemIconColor="#CCC"
          itemTextColor="#000"
          displayKey="name"
          searchInputStyle={{ color: '#CCC' }}
          submitButtonColor="#CCC"
          submitButtonText="Submit"
        />
        <View>

The problem is with the submit button. I only want to record the items selected once the user has pressed submit.

At the moment it logs that the button was pressed every time a new item is selected and that does not help with storing the items selected into another array.

Any help would be great.


Solution

  • You can do this to get an array with the item objects that are selected:

    for(var i = 0; i < selectedItems.length; i++){
    this.state.selectedItemsArray.push(this.state.gasOptions[selectedItems[i]])
    }
    console.log(selectedItems);
    

    This should output the array of items that are selected with each item containing the unique key and the display name.