I am trying to use multiselect feature of react-native-dropdown-picker which is working fine for selecting item, I can select multiple Items and can get its values too, but my problem is I am not able to show defaultValue on screen load.

I am fetching data from server and then trying to show on dropdown-picker

const AccountSelection = (props) => {
      const [accountId, setAccount] = useState([])
      const [accountList, setAccountList] = useState([])
      const [defaultAccount, setDefaultAccount] = useState([])

      useEffect(() => {
        getAccounts()      
      }, [])

      const getAccounts = () => {
        axiosConfig.get('/accounts')
            .then((response) => {
                if (response.status == 200) {
                    const accountData = response.data.payload.data
                        const accountNames = accountData.map((item) => ({ label: item.name, value: item.id, selected: item.id == store.usersDefaultValues.account_id ? true : false }))
                        setAccountList(accountNames)
                        setDefaultAccount(accountNames.find(item => item.selected == true ? item.value : null))
                    }
                }
            })
            .catch((error) => {
                console.log("axios error", error);
            })
       }

       return (
                <View>
                    <DropDownPicker
                        placeholder="Select Account"
                        value={accountId}
                        items={accountList}
                        onChangeItem={(val) => setAccountId(val)}
                        defaultValue={defaultAccount}
                        multiple={true}
                        activeItemStyle={{ backgroundColor: '#F5CCF8' }}
                    ></DropDownPicker>
                </View>
        )
 }

On screen Load I am getting blank dropdown-picker, where it should show 1 Item Selected.

enter image description here

In DropDownPickerProps in react-native-dropdown-picker optional selected key is available but it is not working

items: {
      label: any;
      value: any;
      icon?: () => JSX.Element;
      hidden?: boolean;
      disabled?: boolean;
      selected?: boolean;
    }[];

Please share if anyone have solution for this. Thank you.

1

There are 1 best solutions below

0
On

The defaultValue attribute is not longer supported in react-native-dropdown-picker. If you want to select a default value, you simply need to set the 'value' variable to the default value's value.

You can read more in this issue: https://github.com/hossein-zare/react-native-dropdown-picker/issues/511#issuecomment-1049110163.