How to provide Picker a default "Please select..." option?
You can add a conditional to your handleChangeOption so that it would only set state when the value is not 0 (the Please select an option...
Picker). Something like:
handleChangeOption(val) {
if (val !== 0) {
this.setState({selectedValue: val});
}
}
...
<View style={Styles.row}>
<Picker
selectedValue={this.state.selectedValue}
onValueChange={this.handleChangeOption}
prompt='Options'}
>
<Picker.Item label='Please select an option...' value='0' />
<Picker.Item label='option 1' value='1' />
<Picker.Item label='option 2' value='2' />
</Picker>
</View>
Here is how I just achieved it in React Native:
InputPicker Presentational Component:
import React from 'react'
import { StyleSheet, View, Text, Picker } from 'react-native'
const InputPicker = ({
style,
hasError,
title,
enabled,
selectedValue,
onValueChange,
items,
firstItem
}) => {
if (!items || !Array.isArray(items)) return null
const { container, errorContainer, errorText, pickerTitle, pickerItem } = styles
return (
<View style={[container, (hasError) ? errorContainer : null, style]}>
<Text style={[pickerTitle, (hasError) ? errorText : null]}>
{title}
</Text>
<Picker
style={[pickerItem, (hasError) ? errorText : null]}
selectedValue={selectedValue}
onValueChange={onValueChange}
enabled={enabled}>
<Picker.Item key={'unselectable'} label={firstItem} value={0} />
{items.map((c) => <Picker.Item key={c.id} label={c.label} value={c.label} />)}
</Picker>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 0,
flexDirection: 'row',
alignItems: 'center'
},
pickerTitle: {
flex: 1,
textAlign: 'right'
},
pickerItem: {
flex: 2
},
errorContainer: {
backgroundColor: '#F8DEE0',
borderColor: '#DD0426',
borderWidth: 1
},
errorText: {
color: '#DD0426'
}
})
export { InputPicker }
Parent Container View (using Formik form handler)
<CardSection style={{ flex: 0, alignItems: 'center' }}>
<InputPicker
title="City"
enabled
hasError={touched.person_city && errors.person_city}
selectedValue={this.props.person_city}
onValueChange={(value) => {
this.props.setFieldValue('person_city', value)
this.props.updateField({ prop: 'person_city', value })
}}
items={this.getCities()}
firstItem="Select your city"
/>
</CardSection>
Parent Container this.getCities()
getCities() {
const cities = [
{ id: 0, label: 'Nanaimo' },
{ id: 1, label: 'Victoria' },
{ id: 2, label: 'Ladysmith' }
]
return cities
}
It works because it sets value to 0 if "Select your city" is picked, which makes it a falsy value which triggers touched.person_city && errors.person_city
and puts it into an error state.