0.0.2 • Published 5 years ago

expo-sectioned-multi-select v0.0.2

Weekly downloads
48
License
MIT
Repository
github
Last release
5 years ago

react-native-sectioned-multi-select

A multi (or single) select component with support for sub categories, search, chips. It's intended for long-ish lists, as it opens in a Modal (I might make this optional in the future).

This is based on https://github.com/toystars/react-native-multiple-select. The problems I had were that I needed it to be in a modal, because of nested ScrollViews not working on Android, and I needed to display categories with sub-categories.

Changelog

preview 1 preview 2 preview 3 preview 4

Usage

NPM Version

npm i -S expo-sectioned-multi-select

Required props:
items | array
uniqueKey | string
onSelectedItemsChange | function

import React, { Component } from 'react';
import {
  View
} from 'react-native';
import SectionedMultiSelect from 'expo-sectioned-multi-select';

const icon = require('./icon.png');

const items = [
  {  
    name: "Fruits",
    id: 0,
    icon: icon, // local required file
    children: [{
        name: "Apple",
        id: 10,
      },{
        name: "Strawberry",
        id: 17,
      },{
        name: "Pineapple",
        id: 13,
      },{
        name: "Banana",
        id: 14,
      },{
        name: "Watermelon",
        id: 15,
      },{
        name: "Kiwi fruit",
        id: 16,
      }]
  },
  {
    name: "Gems",
    id: 1,
    icon: { uri: "https://cdn4.iconfinder.com/data/icons/free-crystal-icons/512/Gemstone.png" } // web uri
    children: [{
        name: "Quartz",
        id: 20,
      },{
        name: "Zircon",
        id: 21,
      },{
        name: "Sapphire",
        id: 22,
      },{
        name: "Topaz",
        id: 23,
      }]
  },
  {
    name: "Plants",
    id: 2,
    icon: "filter_vintage" // material icons icon name
    children: [{
        name: "Mother In Law\'s Tongue",
        id: 30,
      },{
        name: "Yucca",
        id: 31,
      },{
        name: "Monsteria",
        id: 32,
      },{
        name: "Palm",
        id: 33,
      }]
  },
]

export default class App extends Component {
  constructor(){
    super()
    this.state = {
      selectedItems: [],
    }
  }
  onSelectedItemsChange = (selectedItems) => {
    this.setState({ selectedItems });
  }

  render() {
    return (
      <View>
      
        <SectionedMultiSelect
          items={items} 
          uniqueKey='id'
          subKey='children'
          iconKey='icon'
          selectText='Choose some things...'
          showDropDowns={true}
          readOnlyHeadings={true}
          onSelectedItemsChange={this.onSelectedItemsChange}
          selectedItems={this.state.selectedItems}
        />

      </View>
    );
  }
}

You can programatically remove all items by setting up a ref to the component:

<SectionedMultiSelect
    ...
    ref={SectionedMultiSelect => this.SectionedMultiSelect = SectionedMultiSelect}
/>

and then use the _removeAllItems function:

onPress={() => this.SectionedMultiSelect._removeAllItems()}

You can open the modal programatically with the _toggleSelector() method:

onPress={() => this.SectionedMultiSelect._toggleSelector()}

Items

Your items should have a uniqueKey(default: 'id') and a displayKey (default: 'name'). Any child items of that item should be in subKey, and they will have uniqueKey and displayKey properties. As you can see from the example above, my items all have a unique id property and the child items is an array within the subKey property.

Sub categories are optional, there's no need to have subKey items if you don't want to.

Props

Props, there are lots.

Main

PropDefaulttypeDesc
itemsarraythe items
uniqueKey'id'stringthe unique key for your items
subKey'sub'stringthe array of sub items within items
displayKey'name'stringthe key for the display name / title of the item
iconKeystringthe key for the display icon / bitmap of the item
selectedItems[]arraythe selected items
onSelectedItemsChangefunctionfunction that runs when an item is toggled
onSelectedItemObjectsChangefunctionfunction that returns the selected items as their original objects instead of an array of ids
onCancelfunctionfunction that runs when the cancel button is pressed
onConfirmfunctionfunction that runs when the confirm button is pressed
onToggleSelectorfunctioncallback function that runs when the selector is toggled. receives a boolean for the open/close state of the modal

Options

PropDefaulttypeDesc
loadingfalseboolset the loading state, shows loadingComponent if true
singlefalseboolallow only one selection
showDropDownstrueboolwhether to allow dropdown toggles to show/hide the sub items (if false, sub items are always shown)
expandDropDownsfalseboolwhen using showDropDowns, set to true to expand all the dropdowns on mount
animateDropDownstrueboolwhether to animate toggling of dropdowns
showChipstrueboolwhether to show the chips of the selected items
hideSelectfalseboolhide the select component
hideConfirmfalseboolhide the confirm buttom
showCancelButtonfalseboolShow a cancel button next to the confirm button. Dismisses modal and removes all selected items.
alwaysShowSelectTextfalseboolDon't show number of items selected or the single selected item on the select label (unless single is true).
readOnlyHeadingsfalseboolwhether the parent items can be pressed or not. If true and showDropdowns is true, pressing the parent item will toggle the dropdown
hideSearchfalseboolhide the search bar entirely
selectChildrenfalseboolif true, selecting a parent item will automatically select its children
highlightChildrenfalseboolif true, selecting a parent item will automatically highlight its children (but the child ids won't be broadcast to the selectedItems state)
showRemoveAllfalseboolWhether to show a Remove all chip at the beginning of the selected items chips
modalSupportedOrientations'landscape', 'portrait'arrayThe supportedOrientations of the Modal
modalAnimationType'fade'stringThe animation type of the Modal (fade or slide)
modalWithSafeAreaViewfalseboolIf true uses a <SafeAreaView> component for the backdrop component. Useful for e.g iPhone X notch
modalWithTouchablefalseboolIf true wraps the backdrop component with <TouchableWithoutFeedback> . Closes modal on press (this._closeSelector(); fires onToggleSelector(false)).

Customization

PropDefaulttypeDesc
selectText'Select'stringthe text for the select component
confirmText'Confirm'stringthe text for the confirm button
selectedText'selected'string OR functionthe text that follows the number of items selected
renderSelectTextfunctionFunction that allows you to set custom Select Text given access to component's props
searchPlaceholderText'Search categories...'stringthe placeholder text for the search input
searchAdornmentfunctionreceives search input text and is output on the right side of the search input
removeAllText'Remove all'stringText for optional remove all button
filterItemsnullfunctionUse a custom filtering function for the search: receives searchText, items, props. Should return an array of item objects.
headerComponentundefinedobjectoptional component to display above the search bar
footerComponentundefinedobjectoptional component to display below the confirm button
stickyFooterComponentundefinedobjectoptional component to display below the confirm button, but outside of the scroll view
noResultsComponentSorry, no resultsobjectthe component to display when the search results are empty
loadingComponentActivityIndicatorobjectthe component to display when loading is set to true
noItemsComponentNo ItemsobjectShown when the items array is empty / null
selectToggleIconComponentMaterial keyboard-arrow-downobjectThe icon to the right of the dropdown in its initial state )
searchIconComponentMaterial searchobjectThe search input icon (default Magnifying glass)
selectedIconComponentMaterial checkobjectThe icon to the left of the selected item (default Checkmark)
dropDownToggleIconUpComponentMaterial keyboard-arrow-upobjectThe parent dropdown icon in closed state
dropDownToggleIconDownComponentMaterial keyboard-arrow-downobjectThe parent dropdown icon in opened state
cancelIconComponentMaterial cancelobjectThe cancel button's inner component
customChipsRendererfunctionUse a custom render function for custom chips: receives uniqueKey, subKey, displayKey, items, selectedItems, colors, styles. should return valid jsx
chipRemoveIconComponentMaterial closeobjectThe chip remove button's icon component
styles{}objectStyles object - see styles section
colors{...}objectcolors object - see colors section
itemFontFamilyAvenir / normal - boldobjectfont family for the parent items. Can be a regular style object
subItemFontFamilyAvenir / normal - 200objectfont family for the sub items. Can be a regular style object
searchTextFontFamilyAvenir / normal - 200objectfont family for the search input. Can be a regular style object
confirmFontFamilyAvenir / normal - boldobjectfont family for the confirm button.
itemNumberOfLinesnullnumbernumberOfLines for item text
selectLabelNumberOfLines1numbernumberOfLines for select label text
customLayoutAnimationeaseInEaseOutobjectdefine your own LayoutAnimation preset or custom animation

Colors

You can pass a colors object to theme it how you like.

These are the available colors and their defaults:

NameDefaultDescription
primary#3f51b5used for the dropdown toggle icon, the no results text and the background of the confirm button.
success#4caf50used for the selected checkmark icon.
cancel#1A1A1Aused for the cancel button background
text#2e2e2eParent item text color
subText#848787Sub item text color
selectToggleTextColor#333Select button text color
searchPlaceholderTextColor#999Search input placeholder text color
searchSelectionColorrgba(0,0,0,0.2)Search input text selection color
itemBackground#fffparent item background color
subItemBackground#ffffffsub item background color
chipColor#848787chip color
disabled#d7d7d7Selected icon color for sub items when highlight children is used

Styles

You can pass a styles object to style it how you like.

These are the styles you can change:
container
listContainer
selectToggle
selectToggleText
item
selectedItem
subItem
itemText selectedItemText
selectedSubItemText subItemText
searchBar
center
separator
subSeparator
chipsWrapper
chipContainer
chipText
chipIcon
searchTextInput
scrollView
button
confirmText
cancelButton
itemIconStyle