skip to Main Content

I use react-native-element-dropdown package in my app.

I want to add dynamic data in the component. But first, I would like to add an empty dropdown option value like:

{label: '-- Please Select --', value: ""}

const dropdownData = () => {
    if(userList){
        return userList?.filter(user => user.id != null).map((user, index)=> {
            return {label: user.username, value: user.id}
        })
    }
}

The dropdownData is called in component’s data property:

<Dropdown data={ dropdownData() } />

How can I add the empty value before the userList map?

2

Answers


  1. Append your hard-coded option to the array before returning:

    const dropdownData = () => {
        if (userList) {
            return [
                { label: '-- Please Select --', value: "" },
                ...userList
                    .filter(user => user.id != null)
                    .map(user => ({ label: user.username, value: user.id }))
            ];
        }
    }
    

    You can do the same in the JSX:

    <Dropdown data={[ ...dropdownData(), { label: '-- Please Select --', value: "" } ]} />
    
    Login or Signup to reply.
  2. try this:

    <Dropdown data={[{label: '-- Please Select --', value: ""}, ...dropdownData()]} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search