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';45interface Props extends Omit<PickerSelectProps, 'onValueChange'> {6 name: string;7}89export default function RNPickerSelect({ name, items, ...rest }: Props) {10 const pickerRef = useRef(null);11 const { fieldName, registerField, defaultValue = '' } = useField(name);1213 const [selectedValue, setSelectedValue] = useState(defaultValue);1415 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]);3031 return (32 <Picker33 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);34 const pickerOptions = [5 { value: 'diego3g', label: 'Diego Fernandes' },6 { value: 'EliasGcf', label: 'Elias Gabriel' },7 ];89 function handleSubmit(data) {10 /**11 * Out example when 'Diego Fernandes' marked: { user: "diego3g" }12 * You get a string with the value13 */14 console.log(data);15 }1617 return (18 <View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>19 <Form20 ref={formRef}21 onSubmit={handleSubmit}22 initialData={{ user: pickerOptions[0].value }}23 >24 <RNPickerSelect name="user" items={pickerOptions} />2526 <Button27 onPress={() => formRef.current.submitForm()}28 title="console.log"29 />30 </Form>31 </View>32 );33};