react native-tutorial

React Native Select Dropdown

The React Native Picker component is used to choose an item from a variety of options. This is equivalent to a drop-down menu item. When we need to give a choice among several possibilities, we utilise a picker.

The Picker component from the react-native library is imported to use it.

Syntax

<Picker>
    <Picker.Item />
    <Picker.Item />
    <Picker.Item />
</Picker>

Properties

  • enabled: If it is false then the user will not able to make a selection.
  • itemStyle: It is used to style the item label.
  • mode: It decides how the selected items will be displayed, and it is only available on the android platform.
  • onValueChange: It is a callback function when the item is selected, and it takes two arguments first is changed value, and second is the index of the item.
  • prompt: It displays as a title of the dialog box, and it is only available on the android platform.
  • selectedValue: It shows the selected value.
  • style: It basically styles the picker.
  • testID: It is used to locate this view in end-to-end tests.

Installation

If you are using Expo then just execute the command below to install the package:

expo install @react-native-picker/picker

For non-expo projects:

npm i @react-native-picker/picker

If you are developing an app for iOS, you need to perform an extra command:

npx pod-install

The Code

App.js

import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";

import { Picker } from "@react-native-picker/picker";

function App() {
  const [country, setCountry] = useState('Unknown');

  return (
    <View style={styles.screen}>
      <Text style={styles.text}>KindaCode.com</Text>
      <Picker
        selectedValue={country}
        onValueChange={(value, index) => setCountry(value)}
        mode="dropdown" // Android only
        style={styles.picker}
      >
        <Picker.Item label="Please select your country" value="Unknown" />
        <Picker.Item label="Australia" value="Australia" />
        <Picker.Item label="Belgium" value="Belgium" />
        <Picker.Item label="Canada" value="Canada" />
        <Picker.Item label="India" value="India" />
        <Picker.Item label="Japan" value="Japan" />
      </Picker>
      <Text style={styles.text}>Your conuntry: {country}</Text>
    </View>
  );
}

export default App;

// Just some styles
const styles = StyleSheet.create({
  screen: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: 'yellow'
  },
  text: {
    fontSize: 24,
  },
  picker: {
    marginVertical: 30,
    width: 300,
    padding: 10,
    borderWidth: 1,
    borderColor: "#666",
  },
});

Output

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *