react-native-element-dropdown
react-native-element-dropdown copied to clipboard
Group the dropdown options with header.
Currently i didn’t find any prop or option to add header to my options.
I just attached an image what i am trying to achieve.
I am very thankful if you accept my feature or improvement request. @hoaphantn7604
Just thought I'd share how I was able to achieve this, there are a couple things to consider.
- Insert the group headers as objects in the data:
const data = [
{ label: 'Recent', name: '', isGroupLabel: true }, // Group header
...recents.map(item => ({ ...item, group: 'Recent' })),
{ label: 'All Counters', name: '', isGroupLabel: true }, // Group header
...others.map(item => ({ ...item, group: 'Other' })),
]
- Build the custom render method to render the dropdown items. Note that in order to prevent the headers from being selectable, you must use the
preventDefault
function on the press event:
const renderItem = item => {
if (item?.isGroupLabel) {
// Render group labels differently
return (
<BrandedText
style={{ fontWeight: 'bold', fontSize: 16, padding: 10 }}
onPress={e => e.preventDefault()}
>
{item.label}
</BrandedText>
)
} else {
// Render regular items
return (
<View style={{ padding: 10 }}>
<BrandedText>{item.name}</BrandedText>
</View>
)
}
}
- Pass custom render to component:
<Dropdown
data={data}
search
labelField="name"
valueField="id"
value={selectedValue}
onFocus={() => setIsFocus(true)}
onBlur={() => setIsFocus(false)}
onChange={item => {
setSelectedValue(item.id)
setIsFocus(false)
}}
renderItem={renderItem} // Here
/>