2

How do i implement multiple select dropdown in react native? I have tried MultiSelect (https://github.com/toystars/react-native-multiple-select) from react-native-multiple-select but it is not working.

3
  • Could you please share your piece of code? Commented Oct 11, 2017 at 7:04
  • I have done on this link stackoverflow.com/questions/46646491/… Commented Oct 11, 2017 at 7:21
  • @wlisrausr please go through the above comment Commented Oct 13, 2017 at 5:02

2 Answers 2

4

This is a source code of implemented multiselect source list

import React from 'react';
import {View, Text, StyleSheet, FlatList, TouchableHighlight, Dimensions} from 'react-native';
var thisObj;
var deviceHeight = Dimensions.get("window").height;

class MyListItem extends React.PureComponent {

    render() {
        return (
            <View style={{flex: 1}}>
                <TouchableHighlight onPress={this.props.onPress.bind(this)} underlayColor='#616161'>
                    <Text style={this.props.style}>{this.props.item.key}</Text>
                </TouchableHighlight>
            </View>
            );
    }
}

export default class MultiSelect extends React.Component {
    constructor(props) {
      super(props);
      var selectedItemsObj = {};
      if(this.props.selectedItems) {
          var items = this.props.selectedItems.split(',');
          items.forEach(function(item) {
            selectedItemsObj[item] = true;
          });   
      }
      this.state = {
        selectedItems: selectedItemsObj
      };
    }

    onItemPressed(item) {
        var oldSelectedItems = this.state.selectedItems;
        var itemState = oldSelectedItems[item.key];
        if(!itemState) {
            oldSelectedItems[item.key] = true;
        }
        else {
            var newState = itemState? false: true;
            oldSelectedItems[item.key] = newState;
        }
        this.setState({
            selectedItems: oldSelectedItems,
        });
        var arrayOfSelectedItems = [];
        var joinedItems = Object.keys(oldSelectedItems);
        joinedItems.forEach(function(key) {
            if(oldSelectedItems[key])
                arrayOfSelectedItems.push(key);
        });
        var selectedItem = null;
        if(arrayOfSelectedItems.length > 0)
            selectedItem = arrayOfSelectedItems.join();
        this.props.onValueChange(selectedItem);
    }

    componentWillMount() {
        thisObj = this;
    }

    getStyle(item) {
        try {
            console.log(thisObj.state.selectedItems[item.key]);
            return thisObj.state.selectedItems[item.key]? styles.itemTextSelected : styles.itemText;
        } catch(e) {
            return styles.itemText;
        }
    }

    _renderItem = ({item}) => {
        return (<MyListItem style={this.getStyle(item)} onPress={this.onItemPressed.bind(this, item)} item={item} />);
    }
    render() {
        return (
            <View style={styles.rootView}>
                <FlatList style={styles.list}
                    initialNumToRender={10}
                    extraData={this.state}
                    data={this.props.data}
                    renderItem={this._renderItem.bind(this)}
                    />
            </View>
            );
    }
}

const styles = StyleSheet.create({
    rootView : {
        height: deviceHeight / 2
    },
    itemText: {
        padding: 8,
        color: "#fff"
    },
    itemTextSelected: {
        padding: 8,
        color: "#fff",
        backgroundColor: '#757575'
    },
    list: {
        flex: 1,
    }
});

This is how the component should be used

this.state = {
        selectedItem : null,
        data: [{key:"key1", label:"label1"}, {key:"key2", label:"label2"}]
      } 

...

<MultiSelect 
                data={this.state.data} 
                selectedItems={this.state.selectedItem} 
                onValueChange={ (itemValue) => thisObj.setState({selectedItem: itemValue})}/>

Selected values will be joined and set in this.state.selectedItem field

Sign up to request clarification or add additional context in comments.

2 Comments

the list of Item that is to be display in dropdown are fetching from the API is in JSON format. How do i convert to this format [{key:"key1", label:"label1"}, {key:"key2", label:"label2"}]
You should to do something like this var resultsArray = []; fetch(url) .then((response) => response.json()) .then((responseJson) => { responseJson.forEach(function(item) { resultArray.push({ key : item.somekey, label: item.someLabel }); }); this.setState({ data : resultsArray, showModal: true }) }) })
2

I have implemented React Native component. Source code is attached. It shows how to make list checkable. It may be a base for your solution. Please see.

import React from 'react';
import {View, Text, StyleSheet, FlatList, TouchableHighlight} from 'react-native';

var thisObj;

export default class MultiSelect extends React.Component {
    constructor(props) {
      super(props);

  this.state = {
    selectedItems: {}
  };
}

onItemPressed(item) {
    var oldSelectedItems = this.state.selectedItems;
    var itemState = oldSelectedItems[item.key];
    if(!itemState) {
        oldSelectedItems[item.key] = true;
    }
    else {
        var newState = itemState? false: true;
        oldSelectedItems[item.key] = newState;
    }
    this.setState({
        selectedItems: oldSelectedItems,
    });
}

componentDidMount() {
    thisObj = this;
}

getStyle(item) {
    try {
        console.log(thisObj.state.selectedItems[item.key]);
        return thisObj.state.selectedItems[item.key]? styles.itemTextSelected : styles.itemText;
    } catch(e) {
        return styles.itemText;
    }
}

render() {
    return (
        <View style={styles.rootView}>
            <FlatList style={styles.list}
                extraData={this.state}
                data={this.props.data}
                  renderItem={({item}) => 
                    <TouchableHighlight onPress={this.onItemPressed.bind(this, item)} underlayColor='#f00'>
                        <Text style={this.getStyle(item)}>{item.key}</Text>
                    </TouchableHighlight>
                  }
                />
        </View>
        );
}
}

const styles = StyleSheet.create({
rootView : {

},
itemText: {
    padding: 16,
    color: "#fff"
},
itemTextSelected: {
    padding: 16,
    color: "#fff",
    backgroundColor: '#f00'
},
list: {

}
});

How to use this

<Multiselect data = { [{"key" : "item1"}, {"key" : "item2"}{"key" : "item3"}]
}\>

3 Comments

Thanks @Dmytro Marchuk, I have tried your code but unable to produce the result. I would be very happy if you could suggest some other options.
do you have any other option available?? @Dmytrom
I have implemented multiselect flat list, but not dropdown. Do you need source code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.