Search code examples
react-nativereact-native-flatlist

How to multiselect items in flatlist react native


How to multi select and highlight the components in a react native flatlist. I have checked the doc. But it is bit confusing can anybody help me. I have done single select using this method.Could any one modify this to a multi select.I will give the snack link here where i have done the single select

import * as React from 'react';
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import Constants from 'expo-constants';

const Data = [
  {
    id: 1,
    first_name: 'Sile',
  },
  {
    id: 2,
    first_name: 'Clementia',
  },
  {
    id: 3,
    first_name: 'Brita',
  },
  {
    id: 4,
    first_name: 'Duke',
  },
  {
    id: 5,
    first_name: 'Hedvig',
  },
  {
    id: 6,
    first_name: 'Paulie',
  },
  {
    id: 7,
    first_name: 'Munmro',
  },
  {
    id: 8,
    first_name: 'Dyanna',
  },
  {
    id: 9,
    first_name: 'Shanta',
  },
  {
    id: 10,
    first_name: 'Bambi',
  },
];

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItem: null,
    };
  }

  onPressHandler(id) {
    this.setState({ selectedItem: id });
  }

  render() {
    return (
      <View>
        <FlatList
          extraData={this.state.selectedItem} //Must implemented
          //horizontal={true}
          data={Data}
          keyExtractor={item => item.id.toString()}
          showsHorizontalScrollIndicator={false}
          renderItem={({ item }) => (
            <TouchableOpacity onPress={() => this.onPressHandler(item.id)}>
              <Card
                style={
                  this.state.selectedItem === item.id
                    ? {
                        padding: 10,
                        borderRadius: 5,
                        backgroundColor: '#000000',
                      }
                    : {
                        padding: 10,
                        borderRadius: 5,
                        backgroundColor: '#a1a1a1',
                      }
                }>
                <Text>{item.first_name}</Text>
              </Card>
            </TouchableOpacity>
          )}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({

});

this is the sample data


Solution

  • I have made some changes and made your flatlist as multiselect. Please visit this link.

    I have made below changes for making this as multiselect:

    • Added dummy data in state & passed it to flatlist's data.
    • On item press iterate data and for corresponding item set item.selected=true.
    • Inside flatlist's renderItem if item.selected==true then show selection else remove selection.

    Please check and let me know.