Unform

React Native Picker Select

React Native Picker Select

React Native Picker Select component for React Native which emulates the native <select> interfaces for iOS and Android.

⚠️ All examples below are using TypeScript. If you're not using it, you can remove all type definitions from the component definition.

Click here to access a React Native Picker Select Live Demo.

Picker Component

1import React, { useEffect, useRef, useState } from 'react';
2import Picker, { PickerSelectProps } from 'react-native-picker-select';
3import { useField } from '@unform/core';
4
5interface Props extends Omit<PickerSelectProps, 'onValueChange'> {
6 name: string;
7}
8
9export default function RNPickerSelect({ name, items, ...rest }: Props) {
10 const pickerRef = useRef(null);
11 const { fieldName, registerField, defaultValue = '' } = useField(name);
12
13 const [selectedValue, setSelectedValue] = useState(defaultValue);
14
15 useEffect(() => {
16 registerField({
17 name: fieldName,
18 ref: pickerRef.current,
19 getValue: ref => {
20 return ref.props.value || '';
21 },
22 clearValue: ref => {
23 ref.props.onValueChange(ref.props.placeholder.value);
24 },
25 setValue: (_, value: string) => {
26 setSelectedValue(value);
27 },
28 });
29 }, [fieldName, registerField]);
30
31 return (
32 <Picker
33 ref={pickerRef}
34 value={selectedValue}
35 onValueChange={setSelectedValue}
36 items={items}
37 {...rest}
38 />
39 );
40};

Usage example

1export default function App() {
2 const formRef = useRef<FormHandles>(null);
3
4 const pickerOptions = [
5 { value: 'diego3g', label: 'Diego Fernandes' },
6 { value: 'EliasGcf', label: 'Elias Gabriel' },
7 ];
8
9 function handleSubmit(data) {
10 /**
11 * Out example when 'Diego Fernandes' marked: { user: "diego3g" }
12 * You get a string with the value
13 */
14 console.log(data);
15 }
16
17 return (
18 <View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
19 <Form
20 ref={formRef}
21 onSubmit={handleSubmit}
22 initialData={{ user: pickerOptions[0].value }}
23 >
24 <RNPickerSelect name="user" items={pickerOptions} />
25
26 <Button
27 onPress={() => formRef.current.submitForm()}
28 title="console.log"
29 />
30 </Form>
31 </View>
32 );
33};
Edit this page on GitHub