hoaphantn7604 / react-native-element-dropdown

A react-native dropdown component easy to customize for both iOS and Android.
MIT License
1k stars 173 forks source link

Group the dropdown options with header. #223

Open 2021saad opened 1 year ago

2021saad commented 1 year ago

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.

Screenshot 2023-10-10 at 4 56 27 PM

I am very thankful if you accept my feature or improvement request. @hoaphantn7604

briannicholls commented 9 months ago

Just thought I'd share how I was able to achieve this, there are a couple things to consider.

  1. 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' })),
  ]
  1. 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>
      )
    }
  }
  1. 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
    />