Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a static object before dynamic data map in React?

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: ""}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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: "" } ]} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading