react-native-element-dropdown icon indicating copy to clipboard operation
react-native-element-dropdown copied to clipboard

Group the dropdown options with header.

Open 2021saad opened this issue 1 year ago • 1 comments

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

2021saad avatar Oct 10 '23 11:10 2021saad

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
    />

briannicholls avatar Feb 10 '24 06:02 briannicholls