简体   繁体   中英

How to dynamically add data(dropdown list) from api in react-native-select-dropdown?

I am using react-native-select-dropdown and set data array statically but don't know how to set data array dynamically from apis with id

Code :

  const countries = ["Egypt", "Canada", "Australia", "Ireland"]

  <SelectDropdown
  data={countries}
  // defaultValueByIndex={1}
  // defaultValue={'Egypt'}
  onSelect={(selectedItem, index) => {
    console.log(selectedItem, index);
  }}
  defaultButtonText={"Select"}
  buttonTextAfterSelection={(selectedItem, index) => {
    return selectedItem;
  }}
  rowTextForSelection={(item, index) => {
    return item;
  }}
/>

how to set countries array list dynamically and i need both title and id of selected item, the fetching data from api are:

const countries = [
  {namd: 'Egypt', id: 1},
  {namd: 'Canada', id: 2},
  {namd: 'Australia', id: 3},
  {namd: 'Ireland', id: 4},
];

Here is an example from your code as per your requirement. In below code dropdown menu will show the country names and when you select any one of them, then it will print the selected country and id. You can use the useState hook to manage API calls. I have shown you the example how you can manage the response for dropdown.

You can check this snack example I just made - https://snack.expo.dev/hRpKm2bdg

const countries = [
  {namd: 'Egypt', id: 1},
  {namd: 'Canada', id: 2},
  {namd: 'Australia', id: 3},
  {namd: 'Ireland', id: 4},
];


export default function App() {
  return (
    <View>
     <SelectDropdown
    data={countries}
    onSelect={(selectedItem, index) => {
        console.log('selected Country name ->>>>',selectedItem.namd)
        console.log('selected Country Id ->>>>',selectedItem.id)
    }}
    buttonTextAfterSelection={(selectedItem, index) => {
        // text represented after item is selected
        // if data array is an array of objects then return selectedItem.property to render after item is selected
        return selectedItem.namd
    }}
    rowTextForSelection={(item, index) => {
        // text represented for each item in dropdown
        // if data array is an array of objects then return item.property to represent item in dropdown
        return item.namd
    }}
     />
    </View>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM