Creating A Placeholder For The Picker Component - React Native

125 Views Asked by At

I am creating a placeholder for my picker component. I want the text to appear in grey when the picker component is first rendered and no option is selected. It should not appear as one of the options.

I tried using a normal Picker.item component and conditionally rendering it to give the effect of a temporary placeholder. The code looks something like this,

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


<View style={styles.inputBorder}>
          <Picker
            // Updating category mutable variable everytime a new option is selected
            selectedValue={Category}
            onValueChange={(itemValue, itemIndex) => setCategory(itemValue)}
            style={[
              styles.input,
              Category === "" ? styles.placeholder : styles.picker,
            ]}
            onFocus={() => setPlaceholderview(false)}
            onBlur={() => setPlaceholderview(true)}
          >
            {placeholderview && (
              <Picker.Item label="-----Click to select-----" value="" />
            )}

            {categories.map((item, index) => {
              return <Picker.Item label={item} value={item} key={index} />;
            })}
          </Picker>
        </View>

This should work but it doesn't. Suppose the categories array is ["Food","Fuel","Clothes",...] then when using this method the option Food is not initially selectable. So when the component is first rendered and you focus on the picker component and click on it, it still shows the placeholder text. The rest of the options work just fine.

There are already similar questions on this site but I found none to be like the problem I am facing.

0

There are 0 best solutions below