Home > database >  How to deselect an already selected item in the react-native-dropdown-picker?
How to deselect an already selected item in the react-native-dropdown-picker?

Time:06-15

I'm using react-native-dropdown-picker to implement a dropdown in my react-native mobile app.

Following is my code:

import React, { useState } from 'react';

import { View } from 'react-native';

import DropDownPicker from 'react-native-dropdown-picker';

export default function App() {
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState('');
  const [items, setItems] = useState([
    {label: 'Spain', value: 'spain'},
    {label: 'Madrid', value: 'madrid'},
    {label: 'Barcelona', value: 'barcelona'},
    {label: 'Italy', value: 'italy'},
    {label: 'Rome', value: 'rome'},
    {label: 'Finland', value: 'finland'}
  ]);

  return (
    <View style={{
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingHorizontal: 15
    }}>
      <DropDownPicker
        open={open}
        value={value}
        items={items}
        setOpen={setOpen}
        setValue={setValue}
        setItems={setItems}
      />
    </View>
  );
}

This is the output:

enter image description here

I need to deselect the already selected item, when the user clicks on that selected at the opened dropdown. But could not find any props or method to do so. Thank you so much guys.

Can someone please help me?

CodePudding user response:

I think I might've found a solution, check it out:

import { View } from 'react-native';

import DropDownPicker from 'react-native-dropdown-picker';

export default function App() {
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState('');
  const [items, setItems] = useState([
    {label: 'Spain', value: 'spain'},
    {label: 'Madrid', value: 'madrid'},
    {label: 'Barcelona', value: 'barcelona'},
    {label: 'Italy', value: 'italy'},
    {label: 'Rome', value: 'rome'},
    {label: 'Finland', value: 'finland'}
  ]);
  
   const selectValue =  (currentValue:( ((prevState: string) => string) | string )  ) => {
    let chosenValue = (currentValue as ((prevState: string) => string))()
    if (chosenValue === value) {
      setValue('') // basically here, I reset the value to initial state if the selected value is exactly the same with the previously selected one
    } else {
      setValue(currentValue)
    }
  }

  return (
    <View style={{
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingHorizontal: 15
    }}>
      <DropDownPicker
        open={open}
        value={value}
        items={items}
        setOpen={setOpen}
        setValue={selectValue}
        setItems={setItems}
      />
    </View>
  );
}

  • Related