react-native-element-dropdown

repository·master·Indexed 23 days ago

https://github.com/hoaphantn7604/react-native-element-dropdown

A TypeScript-implemented library for React Native that provides customizable dropdown and multiselect components. It ensures a consistent UI across iOS and Android and allows for extensive customization of font sizes, colors, and animation durations. The package includes a standard Dropdown component, a MultiSelect component for multiple item selection, and a SelectCountry component that supports images.

Tokens
21.3K
Snippets
16
Records
38
Agent score
79%

What's inside react-native-element-dropdown

  1. Overview of react-native-element-dropdown

    master
    React Native Element Dropdown is a library providing customizable dropdown and multiselect components for React Native applications. It is designed to simplify the creation of dropdown menus with a consistent look and feel across both iOS and Android. The library is implemented with TypeScript and allows for extensive customization of font sizes, colors, and animation durations.
  2. Key features of react-native-element-dropdown

    master

    The library includes the following features:

    • Support for both Dropdown and Multiselect components in a single package.
    • Ease of use for React Native developers.
    • Cross-platform consistency (iOS and Android).
    • High customizability for visual elements (font size, colors) and behavior (animation duration).
    • Full TypeScript implementation for type safety.
  3. Configure Dropdown display modes

    master

    The mode prop determines how the dropdown list is displayed:

    • default: The dropdown list appears relative to the trigger element (using _measure to calculate position).
    • modal: The dropdown list is displayed inside a Modal component.
    • auto: Used in conjunction with dropdownPosition to determine if the list should appear above or below the trigger.

    Additionally, use dropdownPosition to force a specific orientation:

    • 'auto': Automatically decides based on available screen space.
    • 'top': Forces the list to appear above the trigger.

    Note: When using mode='modal', the dropdown may appear as a full-screen overlay on tablets or in landscape mode depending on device detection.

  4. Use the MultiSelect component

    master

    The MultiSelect component allows users to select multiple items from a list. It supports searching, custom rendering for items and selected states, and can be used in two modes: as a standalone dropdown or embedded within a container using the inside prop.

    Key features include:

    • Search functionality: Filter items using a search bar.
    • Custom Rendering: Use renderItem, renderSelectedItem, renderLeftIcon, and renderRightIcon to customize the UI.
    • Selection Control: Control the maximum number of items selectable via maxSelect and handle selection confirmation via onConfirmSelectItem and confirmSelectItem props.
    • Ref Access: Use a ref to programmatically open or close the dropdown.
  5. Implement a basic Dropdown component

    master

    To use the Dropdown component, provide a data array, specify the labelField and valueField, and handle the onChange event to update your state. You can also enable search and customize icons using renderLeftIcon or renderRightIcon.

      import React, { useState } from 'react';
      import { StyleSheet, Text, View } from 'react-native';
      import { Dropdown } from 'react-native-element-dropdown';
      import AntDesign from '@expo/vector-icons/AntDesign';
    
    const data = [
        { label: 'Item 1', value: '1' },
        { label: 'Item 2', value: '2' },
        { label: 'Item 3', value: '3' },
        { label: 'Item 4', value: '4' },
        { label: 'Item 5', value: '5' },
        { label: 'Item 6', value: '6' },
        { label: 'Item 7', value: '7' },
        { label: 'Item 8', value: '8' },
      ];
    
    const DropdownComponent = () => {
        const [value, setValue] = useState(null);
        const [isFocus, setIsFocus] = useState(false);
    
    const renderLabel = () => {
          if (value || isFocus) {
            return (
              <Text style={[styles.label, isFocus && { color: 'blue' }]}>
                Dropdown label
              </Text>
            );
          }
          return null;
        };
    
    return (
          <View style={styles.container}>
            {renderLabel()}
            <Dropdown
              style={[styles.dropdown, isFocus && { borderColor: 'blue' }]}
              placeholderStyle={styles.placeholderStyle}
              selectedTextStyle={styles.selectedTextStyle}
              inputSearchStyle={styles.inputSearchStyle}
              iconStyle={styles.iconStyle}
              data={data}
              search
              maxHeight={300}
              labelField="label"
              valueField="value"
              placeholder={!isFocus ? 'Select item' : '...'}
              searchPlaceholder="Search..."
              value={value}
              onFocus={() => setIsFocus(true)}
              onBlur={() => setIsFocus(false)}
              onChange={item => {
                setValue(item.value);
                setIsFocus(false);
              }}
              renderLeftIcon={() => (
                <AntDesign
                  style={styles.icon}
                  color={isFocus ? 'blue' : 'black'}
                  name="Safety"
                  size={20}
                />
              )}
            />
          </View>
        );
      };
    
    export default DropdownComponent;
  6. Implement a basic MultiSelect

    master

    Use the MultiSelect component for selecting multiple items from a list. The value prop should be an array of selected values, and the onChange callback returns the updated array of selected items.

      import React, { useState } from 'react';
      import { StyleSheet, View } from 'react-native';
      import { MultiSelect } from 'react-native-element-dropdown';
      import AntDesign from '@expo/vector-icons/AntDesign';
    
    const data = [
        { label: 'Item 1', value: '1' },
        { label: 'Item 2', value: '2' },
        { label: 'Item 3', value: '3' },
        { label: 'Item 4', value: '4' },
        { label: 'Item 5', value: '5' },
        { label: 'Item 6', value: '6' },
        { label: 'Item 7', value: '7' },
        { label: 'Item 8', value: '8' },
      ];
    
    const MultiSelectComponent = () => {
        const [selected, setSelected] = useState([]);
    
    return (
          <View style={styles.container}>
            <MultiSelect
              style={styles.dropdown}
              placeholderStyle={styles.placeholderStyle}
              selectedTextStyle={styles.selectedTextStyle}
              inputSearchStyle={styles.inputSearchStyle}
              iconStyle={styles.iconStyle}
              search
              data={data}
              labelField="label"
              valueField="value"
              placeholder="Select item"
              searchPlaceholder="Search..."
              value={selected}
              onChange={item => {
                setSelected(item);
              }}
              renderLeftIcon={() => (
                <AntDesign
                  style={styles.icon}
                  color="black"
                  name="Safety"
                  size={20}
                />
              )}
              selectedStyle={styles.selectedStyle}
            />
          </View>
        );
      };
    
    export default MultiSelectComponent;
    
    const styles = StyleSheet.create({
        container: { padding: 16 },
        dropdown: {
          height: 50,
          backgroundColor: 'transparent',
          borderBottomColor: 'gray',
          borderBottomWidth: 0.5,
        },
        placeholderStyle: {
          fontSize: 16,
        },
        selectedTextStyle: {
          fontSize: 14,
        },
        iconStyle: {
          width: 20,
          height: 20,
        },
        inputSearchStyle: {
          height: 40,
          fontSize: 16,
        },
        icon: {
          marginRight: 5,
        },
        selectedStyle: {
          borderRadius: 12,
        },
      });
  7. Implement a basic Dropdown

    master

    Use the Dropdown component to create a single-selection dropdown. You must provide a data array, specify labelField and valueField to map your data objects, and manage the selected value via state. The onChange callback returns the selected item object.

      import React, { useState } from 'react';
      import { StyleSheet } from 'react-native';
      import { Dropdown } from 'react-native-element-dropdown';
      import AntDesign from '@expo/vector-icons/AntDesign';
    
    const data = [
        { label: 'Item 1', value: '1' },
        { label: 'Item 2', value: '2' },
        { label: 'Item 3', value: '3' },
        { label: 'Item 4', value: '4' },
        { label: 'Item 5', value: '5' },
        { label: 'Item 6', value: '6' },
        { label: 'Item 7', value: '7' },
        { label: 'Item 8', value: '8' },
      ];
    
    const DropdownComponent = () => {
        const [value, setValue] = useState(null);
    
    return (
          <Dropdown
            style={styles.dropdown}
            placeholderStyle={styles.placeholderStyle}
            selectedTextStyle={styles.selectedTextStyle}
            inputSearchStyle={styles.inputSearchStyle}
            iconStyle={styles.iconStyle}
            data={data}
            search
            maxHeight={300}
            labelField="label"
            valueField="value"
            placeholder="Select item"
            searchPlaceholder="Search..."
            value={value}
            onChange={item => {
              setValue(item.value);
            }}
            renderLeftIcon={() => (
              <AntDesign style={styles.icon} color="black" name="Safety" size={20} />
            )}
          />
        );
      };
    
    export default DropdownComponent;
    
    const styles = StyleSheet.create({
        dropdown: {
          margin: 16,
          height: 50,
          borderBottomColor: 'gray',
          borderBottomWidth: 0.5,
        },
        icon: {
          marginRight: 5,
        },
        placeholderStyle: {
          fontSize: 16,
        },
        selectedTextStyle: {
          fontSize: 16,
        },
        iconStyle: {
          width: 20,
          height: 20,
        },
        inputSearchStyle: {
          height: 40,
          fontSize: 16,
        },
      });
  8. Implement a searchable dropdown with images

    master

    You can create a highly customized dropdown using the Dropdown component (referred to as SelectCountry in the example) by providing a data array and specifying which fields represent the value, label, and image. To enable searching, include the search prop.

    Key configuration props:

    • data: Array of objects containing your items.
    • valueField: The key in your data objects used for the unique identifier (e.g., 'value').
    • labelField: The key in your data objects used for the display text (e.g., 'lable').
    • imageField: The key in your data objects used for the image object (e.g., 'image').
    • search: Boolean to enable the search bar.
    • onChange: Callback function that receives the selected item object (e.g., e => setCountry(e.value)).
    import React, { useState } from 'react';
    import { StyleSheet } from 'react-native';
    import { SelectCountry } from 'react-native-element-dropdown';
    
    const local_data = [
        {
          value: '1',
          lable: 'Country 1',
          image: {
            uri: 'https://www.vigcenter.com/public/all/images/default-image.jpg',
          },
        },
        // ... other items
      ];
    
    const SelectCountryScreen = _props => {
        const [country, setCountry] = useState('1');
    
    return (
          <SelectCountry
            style={styles.dropdown}
            selectedTextStyle={styles.selectedTextStyle}
            placeholderStyle={styles.placeholderStyle}
            imageStyle={styles.imageStyle}
            iconStyle={styles.iconStyle}
            maxHeight={200}
            value={country}
            data={local_data}
            valueField="value"
            labelField="lable"
            imageField="image"
            placeholder="Select country"
            searchPlaceholder="Search..."
            onChange={e => {
              setCountry(e.value);
            }}
          />
        );
      };
    
    export default SelectCountryScreen;
    
    const styles = StyleSheet.create({
        dropdown: {
          margin: 16,
          height: 50,
          width: 150,
          backgroundColor: '#EEEEEE',
          borderRadius: 22,
          paddingHorizontal: 8,
        },
        imageStyle: {
          width: 24,
          height: 24,
          borderRadius: 12,
        },
        placeholderStyle: {
          fontSize: 16,
        },
        selectedTextStyle: {
          fontSize: 16,
          marginLeft: 8,
        },
        iconStyle: {
          width: 20,
          height: 20,
        },
      });
  9. Customize Dropdown items with renderItem

    master

    To change how individual items appear in the dropdown list, use the renderItem prop. This allows you to return a custom React component for each item, enabling features like showing a checkmark icon next to the currently selected value.

      import React, { useState } from 'react';
      import { StyleSheet, View, Text } from 'react-native';
      import { Dropdown } from 'react-native-element-dropdown';
      import AntDesign from '@expo/vector-icons/AntDesign';
    
    const data = [
        { label: 'Item 1', value: '1' },
        { label: 'Item 2', value: '2' },
        { label: 'Item 3', value: '3' },
        { label: 'Item 4', value: '4' },
        { label: 'Item 5', value: '5' },
        { label: 'Item 6', value: '6' },
        { label: 'Item 7', value: '7' },
        { label: 'Item 8', value: '8' },
      ];
    
    const DropdownComponent = () => {
        const [value, setValue] = useState(null);
    
    const renderItem = item => {
          return (
            <View style={styles.item}>
              <Text style={styles.textItem}>{item.label}</Text>
              {item.value === value && (
                <AntDesign
                  style={styles.icon}
                  color="black"
                  name="Safety"
                  size={20}
                />
              )}
            </View>
          );
        };
    
    return (
          <Dropdown
            style={styles.dropdown}
            placeholderStyle={styles.placeholderStyle}
            selectedTextStyle={styles.selectedTextStyle}
            inputSearchStyle={styles.inputSearchStyle}
            iconStyle={styles.iconStyle}
            data={data}
            search
            maxHeight={300}
            labelField="label"
            valueField="value"
            placeholder="Select item"
            searchPlaceholder="Search..."
            value={value}
            onChange={item => {
              setValue(item.value);
            }}
            renderLeftIcon={() => (
              <AntDesign style={styles.icon} color="black" name="Safety" size={20} />
            )}
            renderItem={renderItem}
          />
        );
      };
    
    export default DropdownComponent;
    
    const styles = StyleSheet.create({
        dropdown: {
          margin: 16,
          height: 50,
          backgroundColor: 'white',
          borderRadius: 12,
          padding: 12,
          shadowColor: '#000',
          shadowOffset: {
            width: 0,
            height: 1,
          },
          shadowOpacity: 0.2,
          shadowRadius: 1.41,
    
    elevation: 2,
        },
        icon: {
          marginRight: 5,
        },
        item: {
          padding: 17,
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        },
        textItem: {
          flex: 1,
          fontSize: 16,
        },
        placeholderStyle: {
          fontSize: 16,
        },
        selectedTextStyle: {
          fontSize: 16,
        },
        iconStyle: {
          width: 20,
          height: 20,
        },
        inputSearchStyle: {
          height: 40,
          fontSize: 16,
        },
      });
  10. Customize MultiSelect with renderSelectedItem

    master

    For advanced MultiSelect usage, use renderSelectedItem to control how selected items appear in the input field. This prop provides the item and an unSelect function, allowing you to create custom 'chips' or 'tags' that users can tap to remove an item from the selection.

      import React, { useState } from 'react';
      import { StyleSheet, View, TouchableOpacity, Text } from 'react-native';
      import { MultiSelect } from 'react-native-element-dropdown';
      import AntDesign from '@expo/vector-icons/AntDesign';
    
    const data = [
        { label: 'Item 1', value: '1' },
        { label: 'Item 2', value: '2' },
        { label: 'Item 3', value: '3' },
        { label: 'Item 4', value: '4' },
        { label: 'Item 5', value: '5' },
        { label: 'Item 6', value: '6' },
        { label: 'Item 7', value: '7' },
        { label: 'Item 8', value: '8' },
      ];
    
    const MultiSelectComponent = () => {
        const [selected, setSelected] = useState([]);
    
    const renderItem = item => {
          return (
            <View style={styles.item}>
              <Text style={styles.selectedTextStyle}>{item.label}</Text>
              <AntDesign style={styles.icon} color="black" name="Safety" size={20} />
            </View>
          );
        };
    
    return (
          <View style={styles.container}>
            <MultiSelect
              style={styles.dropdown}
              placeholderStyle={styles.placeholderStyle}
              selectedTextStyle={styles.selectedTextStyle}
              inputSearchStyle={styles.inputSearchStyle}
              iconStyle={styles.iconStyle}
              data={data}
              labelField="label"
              valueField="value"
              placeholder="Select item"
              value={selected}
              search
              searchPlaceholder="Search..."
              onChange={item => {
                setSelected(item);
              }}
              renderLeftIcon={() => (
                <AntDesign
                  style={styles.icon}
                  color="black"
                  name="Safety"
                  size={20}
                />
              )}
              renderItem={renderItem}
              renderSelectedItem={(item, unSelect) => (
                <TouchableOpacity onPress={() => unSelect && unSelect(item)}>
                  <View style={styles.selectedStyle}>
                    <Text style={styles.textSelectedStyle}>{item.label}</Text>
                    <AntDesign color="black" name="delete" size={17} />
                  </View>
                </TouchableOpacity>
              )}
            />
          </View>
        );
      };
    
    export default MultiSelectComponent;
    
    const styles = StyleSheet.create({
        container: { padding: 16 },
        dropdown: {
          height: 50,
          backgroundColor: 'white',
          borderRadius: 12,
          padding: 12,
          shadowColor: '#000',
          shadowOffset: {
            width: 0,
            height: 1,
          },
          shadowOpacity: 0.2,
          shadowRadius: 1.41,
    
    elevation: 2,
        },
        placeholderStyle: {
          fontSize: 16,
        },
        selectedTextStyle: {
          fontSize: 14,
        },
        iconStyle: {
          width: 20,
          height: 20,
        },
        inputSearchStyle: {
          height: 40,
          fontSize: 16,
        },
        icon: {
          marginRight: 5,
        },
        item: {
          padding: 17,
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        },
        selectedStyle: {
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center',
          borderRadius: 14,
          backgroundColor: 'white',
          shadowColor: '#000',
          marginTop: 8,
          marginRight: 12,
          paddingHorizontal: 12,
          paddingVertical: 8,
          shadowOffset: {
            width: 0,
            height: 1,
          },
          shadowOpacity: 0.2,
          shadowRadius: 1.41,
    
    elevation: 2,
        },
        textSelectedStyle: {
          marginRight: 5,
          fontSize: 16,
        },
      });
  11. Use SelectCountry component

    master

    The SelectCountry component extends the standard Dropdown functionality by adding support for images. It requires an imageField to extract the image from the data items and provides imageStyle for styling the images.

    | Props              | Params               | isRequire | Description                          |
    | ------------------ | -------------------- | --------- | ------------------------------------ |
    | imageField         | String               | Yes       | Extract the image from the data item |
    | imageStyle         | ImageStyle           | No        | Styling for image                    |