1.0.0-alpha.3 • Published 11 months ago

react-native-modal-multi-selector v1.0.0-alpha.3

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

react-native-modal-multi-selector npm version

A cross-platform (iOS / Android), selector/picker component for React Native that is filterable and multi supported, highly customizable and supports sections.

Multi selection functionality has been added to this fork repository

This project was forked from react-native-modal-selector-searchable

Demo

Install

npm i react-native-modal-multi-selector --save

Usage

You can either use this component in its default mode, as a wrapper around your existing component or provide a custom component (where you need to control opening of the modal yourself). In default mode a customizable button is rendered.

See SampleApp for an example how to use this component.

import ModalSelector from 'react-native-modal-multi-selector'

class SampleApp extends Component {

    constructor(props) {
        super(props);

        this.state = {
            textInputValue: ''
        }
    }

    render() {
        let index = 0;
        const data = [
            { key: index++, section: true, label: 'Fruits' },
            { key: index++, label: 'Red Apples' },
            { key: index++, label: 'Cherries' },
            { key: index++, label: 'Cranberries', accessibilityLabel: 'Tap here for cranberries' },
            // etc...
            // Can also add additional custom keys which are passed to the onChange callback
            { key: index++, label: 'Vegetable', customKey: 'Not a fruit' }
        ];

        return (
            <View style={{flex:1, justifyContent:'space-around', padding:50}}>

                // Default mode
                <ModalSelector
                    data={data}
                    initValue="Select something yummy!"
                    onChange={(option)=>{ alert(`${option.label} (${option.key}) nom nom nom`) }} />

                // Multi mode
                 <ModalSelector
                    data={data}
                    selectStyle={{borderColor: "black"}}
                    selectTextStyle={{color: "blue"}}
                    multi={true}
                    onChange={item => { console.log(item) }}
                />

                // Wrapper
                <ModalSelector
                    data={data}
                    initValue="Select something yummy!"
                    supportedOrientations={['landscape']}
                    accessible={true}
                    scrollViewAccessibilityLabel={'Scrollable options'}
                    cancelButtonAccessibilityLabel={'Cancel Button'}
                    onChange={(option)=>{ this.setState({textInputValue:option.label})}}>

                    <TextInput
                        style={{borderWidth:1, borderColor:'#ccc', padding:10, height:30}}
                        editable={false}
                        placeholder="Select something yummy!"
                        value={this.state.textInputValue} />

                </ModalSelector>

                // Custom component
                <ModalSelector
                    data={data}
                    ref={selector => { this.selector = selector; }}
                    customSelector={<Switch onValueChange={() => this.selector.open()} />}
                />
            </View>
        );
    }
}

Data Format

The selector accepts a specific format of data:

[{ key: 5, label: 'Red Apples' }]

Optionally provide a component key which overrides the default label text. Optionally provide a unique testID for each item:

[{
  key: 5,
  label: 'Red Apples',
  // The next keys are optional --
  component: <View style={{backgroundColor: 'red'}}><Text style={{color: 'white'}}>Red Apples custom component ☺</Text></View>,
  testID: '5-red-apples'
}]

If your data has a specific format, you can define extractors of data, example:

this.setState({data: [{ id: 5, name: 'Red Apples' }]});

return (
  <ModalSelector
    data={this.state.data}
    keyExtractor= {item => item.id}
    labelExtractor= {item => item.name}
  />
);

API

Props

PropTypeOptionalDefaultDescription
dataarrayNo[]array of objects with a unique key and label to select in the modal. Optional component overrides label text. Optional unique testID for each item.
searchboolYestrueControl the search box visibility
hideSectionOnSearchboolYesfalseHide the caption of related matched items
caseSensitiveSearchboolYesfalseSensitive mode on search
frozenSearchboolYesfalsePreserve initial modal size on search
fullHeightboolYesfalseKeep the modal size to the maximum regardless of the listed items
onSearchFiltererfunctionYes(searchText, data) => filteredDataCustom search filterer function.
onChangefunctionYes() => {}callback function, when the users has selected an option
onChangeSearchfunctionYes(searchData) => {}Callback function, when the users has typed in search box
onModalOpenfunctionYes() => {}callback function, when modal is opening
onModalClosefunctionYes(item) => {}callback function, when modal is closing. Returns the selected item.
onCancelfunctionYes() => {}callback function, when clicking the cancel button
keyExtractorfunctionYes(data) => data.keyextract the key from the data item
labelExtractorfunctionYes(data) => data.labelextract the label from the data item
componentExtractorfunctionYes(data) => data.componentextract the component from the data item
visibleboolYesfalsecontrol open/close state of modal
closeOnChangeboolYesIn single mode true In multi mode falsecontrol if modal closes on select
initValuestringYesSelect me!text that is initially shown on the button (available in single mode only!)
cancelTextstringYescanceltext of the cancel button
searchTextstringYessearchtext of the search placeholder
disabledboolYesfalsetrue disables opening of the modal
supportedOrientations'portrait', 'landscape'Yesbothorientations the modal supports
keyboardShouldPersistTapsstring / boolYesalwayspassed to underlying ScrollView
listTypestringYesSCROLLVIEWscroller type: SCROLLVIEW or FLATLIST
animationTypestringYesslidetype of animation to be used to show the modal. Must be one of none, slide or fade.
styleobjectYesstyle definitions for the root element
childrenContainerStyleobjectYes{}style definitions for the children container view
touchableStyleobjectYes{}style definitions for the touchable element
touchableActiveOpacitynumberYes0.2opacity for the touchable element on touch
selectStyleobjectYes{}style definitions for the select element (available in default mode only!). NOTE: Due to breaking changes in React Native, RN < 0.39.0 should pass flex:1 explicitly to selectStyle as a prop.
selectTextStyleobjectYes{}style definitions for the select element (available in default mode only!)
overlayStyleobjectYes{ flex: 1, padding: '5%', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.7)' }style definitions for the overlay background element. RN <= 0.41 should override this with pixel value for padding.
sectionStyleobjectYes{}style definitions for the section element
sectionTextStyleobjectYes{}style definitions for the select text element
optionStyleobjectYes{}style definitions for the option element
optionTextStyleobjectYes{}style definitions for the option text element
optionSelectedStyleobjectYes{ padding: 8, borderBottomWidth: 1, borderBottomColor: '#ccc' }style definitions for the selected option elements
optionSelectedTextStyleobjectYes{ textAlign: 'center', fontSize: FONT_SIZE, color: 'rgba(255, 0, 59, 0.9)' }style definitions for the selected option text elements
optionContainerStyleobjectYes{}style definitions for the option container element
cancelStyleobjectYes{}style definitions for the cancel element
cancelTextStyleobjectYes{}style definitions for the cancel text element
initValueTextStyleobjectYes{}style definitions for the initValue text element (available in single mode only!)
cancelContainerStyleobjectYes{}style definitions for the cancel container
searchStyleobjectYes{}Style definitions for the search view element
searchTextStyleobjectYes{}Style definitions for the search text element
backdropPressToCloseboolYesfalsetrue makes the modal close when the overlay is pressed
passThruPropsobjectYes{}props to pass through to the container View and each option TouchableOpacity (e.g. testID for testing)
selectTextPassThruPropsobjectYes{}props to pass through to the select text component
optionTextPassThruPropsobjectYes{}props to pass through to the options text components in the modal
cancelTextPassThruPropsobjectYes{}props to pass through to the cancel text components in the modal
scrollViewPassThruPropsobjectYes{}props to pass through to the internal ScrollView
openButtonContainerAccessibleboolYesfalsetrue enables accessibility for the open button container. Note: if false be sure to define accessibility props directly in the wrapped component.
listItemAccessibleboolYesfalsetrue enables accessibility for data items. Note: data items should have an accessibilityLabel property if this is enabled
cancelButtonAccessibleboolYesfalsetrue enables accessibility for cancel button.
scrollViewAccessibleboolYesfalsetrue enables accessibility for the scroll view. Only enable this if you don't want to interact with individual data items.
scrollViewAccessibilityLabelstringYesundefinedAccessibility label for the modal ScrollView
cancelButtonAccessibilityLabelstringYesundefinedAccessibility label for the cancel button
modalOpenerHitSlopobjectYes{}How far touch can stray away from touchable that opens modal (RN docs)
customSelectornodeYesundefinedRender a custom node instead of the built-in select box.
selectedKeyanyYes''Key of the item to be initially selected
enableShortPressboolYestrueenables short press. This is regular touch behavior.
enableLongPressboolYesfalseenables long press. When true, onModalOpen returns {longPress: true}
optionsTestIDPrefixstringYes'default'This prefixes each selectable option's testID prop if no testID keys are provided in props.data array objects. Default for each option's testID: 'default-\<optionLabel>'
multiboolYesfalseenables multiple selection mode
textfunctionYes(count) => '${count} item(s) selected'text of dropdown in multi mode

Methods

getSelectedItem(): get current selected item(s) (returns object in single mode, returns array of object in multi mode), updated by onChange event.