MultiSelected List in React Native

MultiSelected List in React Native

In today’s code-read, I read through how to implement multi-selected inputs. All we need to do is to control an array with selected items.  let’s say in our demo user can select his favorite brands from a list of options.

First, we need to show all the inputs to the user. We can use FlatList to render the items. Like so –

const BRANDS = [
  {
    name: 'Toyota',
    slug: 'toyota',
  },
  {
    name: 'Mazda',
    slug: 'mazda',
  },
  {
    name: 'Honda',
    slug: 'honda',
  },
  {
    name: 'Tesla',
    slug: 'tesla',
  },
.....]

export default function App() {
  const [brands, setBrands] = React.useState(BRANDS);
  const [selectedBrands, setSelectedBrands] = React.useState([]);

  const renderBrands = ({ item, index }) => {
    const { name, slug } = item;
  
    return (
      <TouchableOpacity
        onPress={() => {}}
        style={[styles.item]}>
        <Text>{name}</Text>
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={brands}
        renderItem={renderBrands}
        numColumns={4}
        scrollEnabled={false}
      />
    </View>
  );
}

Then we need to keep track of the items that the user is selecting. We can keep track of them using an array. We have two conditions – When an item is already selected and when the item is not selected. So every time the user clicks on an item we need to check if it has been already selected, if it is already selected then we need to remove the item from the selected items, if not then we need to add the item to the selected items list.

We can also change the color of the button and text according to the condition. This is how our renderBrands function looks like after the proper change.

  const renderBrands = ({ item, index }) => {
    const { name, slug } = item;

    const isSelected = selectedBrands.filter((i) => i === slug).length > 0; // checking if the item is already selected

    return (
      <TouchableOpacity
        onPress={() => {
          if (isSelected) {
            setSelectedBrands((prev) => prev.filter((i) => i !== slug));
          } else {
            setSelectedBrands(prev => [...prev, slug])
          }
        }}
        style={[styles.item, isSelected && { backgroundColor: 'black'}]}>
        <Text style={{ color: isSelected ? "white" : "black"}}>{name}</Text>
      </TouchableOpacity>
    );
  };

The complete code can be seen in the following snack. https://snack.expo.io/@saad-bashar/68cb24

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *