sanpyaelin / react-native-ios-picker

ios picker for react native
MIT License
9 stars 7 forks source link

how to set initial value in picker box #3

Open HassanMehdi17 opened 5 years ago

HassanMehdi17 commented 5 years ago

i have a picker in my application used to choose which state the user is in.

the issue is i cant find a way for it to say anything other than the default "Select one". and once you tap anywhere on the screen the box goes blank. only being filled once you make a selection.

ISSUE : I want the box to say "select state" until you actually make a selection

initial press

here is my code

                    <IOSPicker style={styles.picker}  
                        selectedValue={this.state.RegistrationInfo.State} 
                        mode='modal'
                        onValueChange={(itemValue,itemIndex) => this.setState({ RegistrationInfo: { ...this.state.RegistrationInfo, State: itemValue}})}
                    >
                        <Picker.Item label="Alabama"       value="Alabama"       />
                        <Picker.Item label="Alaska"        value="Alaska"        />
                        <Picker.Item label="Arizona"       value="Arizona"       />
                        <Picker.Item label="Arkansas"      value="Arkansas"      />
                        <Picker.Item label="California"    value="California"    />
                        <Picker.Item label="Colorado"      value="Colorado"      />
                        <Picker.Item label="Connecticut"   value="Connecticut"   />
                        <Picker.Item label="Delaware"      value="Delaware"      />
                        <Picker.Item label="Florida"       value="Florida"       />
                        <Picker.Item label="Georgia"       value="Georgia"       />
                        <Picker.Item label="Hawaii"        value="Hawaii"        />
                        <Picker.Item label="Idaho"         value="Idaho"         />
                        <Picker.Item label="Illinois"      value="Illinois"      />
                        <Picker.Item label="Indiana"       value="Indiana"       />
                        <Picker.Item label="Iowa"          value="Iowa"          />
                        <Picker.Item label="Kansas"        value="Kansas"        />
                        <Picker.Item label="Kentucky"      value="Kentucky"      />
                        <Picker.Item label="Louisiana"     value="Louisiana"     />
                        <Picker.Item label="Maine"         value="Maine"         />
                        <Picker.Item label="Maryland"      value="Maryland"      />
                        <Picker.Item label="Massachusetts" value="Massachusetts" />
                        <Picker.Item label="Michigan"      value="Michigan"      />
                        <Picker.Item label="Minnesota"     value="Minnesota"     />
                        <Picker.Item label="Mississippi"   value="Mississippi"   />
                        <Picker.Item label="Missouri"      value="Missouri"      />
                        <Picker.Item label="Montana"       value="Montana"       />
                        <Picker.Item label="Nebraska"      value="Nebraska"      />
                        <Picker.Item label="Nevada"        value="Nevada"        />
                        <Picker.Item label="New Hampshire" value="New Hampshire" />
                        <Picker.Item label="New Jersey"    value="New Jersey"    />
                        <Picker.Item label="New Mexico"    value="New Mexico"    />
                        <Picker.Item label="New York"      value="New York"      />
                        <Picker.Item label="North Carolina"value="North Carolina"/>
                        <Picker.Item label="North Dakota"  value="North Dakota"  />
                        <Picker.Item label="Ohio"          value="Ohio"          />
                        <Picker.Item label="Oklahoma"      value="Oklahoma"      />
                        <Picker.Item label="Oregon"        value="Oregon"        />
                        <Picker.Item label="Pennsylvania"  value="Pennsylvania"  />
                        <Picker.Item label="Rhode Island"  value="Rhode Island"  />
                        <Picker.Item label="South Carolina"value="South Carolina"/>
                        <Picker.Item label="South Dakota"  value="South Dakota"  />
                        <Picker.Item label="Tennessee"     value="Tennessee"     />
                        <Picker.Item label="Texas"         value="Texas"         />
                        <Picker.Item label="Utah"          value="Utah"          />
                        <Picker.Item label="Vermont"       value="Vermont"       />
                        <Picker.Item label="Virginia"      value="Virginia"      />
                        <Picker.Item label="Washington"    value="Washington"    />
                        <Picker.Item label="West Virginia" value="West Virginia" />
                        <Picker.Item label="Wisconsin"     value="Wisconsin"     />
                        <Picker.Item label="Wyoming"       value="Wyoming"       />
                    </IOSPicker>
zarttash-zafar commented 5 years ago

Facing same problem here is my code

const dataselect = ['Select your gender','Male','Female','Other']

constructor(props) {
        super(props)
        this.state = {
            gender: "Select your gender",
        }
    }

change(d, i) {
    this.setState({gender: d});
}

<IOSPicker
        mode={'modal'}
        data={dataselect}
        selectedValue={'Male'}
  onValueChange={(d, i)=> this.change(d, i)}/>

Selected value should be "Male" but it is "Select your gender" help me if am doing something wrong Thanks in advance

zarttash-zafar commented 5 years ago

I solve my problem :-) as i am using array ['Select your gender','Male','Female','Other'] in react-native-ios-picker -> src -> index.js on line no 27 there is condition

if(this.props.data !==null) {
      selected = this.props.data[this.props.selectedValueIndex || 0];
    } else {
      selected = this.props.selectedValue || 'select one';
    } 

this.props.data was always !==null but this.props.selectedValueIndex was undefined because i am using simple array so i changed that code to


if(this.props.data !=null && this.props.selectedValueIndex) {
      selected = this.props.data[this.props.selectedValueIndex || 0];
    } else {
      selected = this.props.selectedValue || 'select one';
    }

just added && this.props.selectedValueIndex now it is working fine for me like a little hack ;-)

Udate

I have updated the code and working fine for me now initial value in picker will be selected

Setps to follow are

  1. Update the code bellow code in react-native-ios-picker -> src -> index.js
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import CollapseView from 'react-native-collapse-view';
import { Text, View, TouchableOpacity , StyleSheet, Picker, Modal } from 'react-native';

const propTypes = {
  mode: PropTypes.string,
  selectedValue: PropTypes.string,
  selectedValueIndex: PropTypes.string,
  onValueChange: PropTypes.func,
  data: PropTypes.array,
  style: PropTypes.object,
  textStyle: PropTypes.object,
  pickerItemStyle: PropTypes.object,
  collapseViewStyle: PropTypes.object,
}

const defaultProps = {
  data: null,
  mode: 'collapse',
};

class IOSPicker extends Component {
  constructor(props) {
    super(props);
    let selected = 0;
    if(this.props.data !=null && this.props.selectedValueIndex) {
      selected = this.props.data[this.props.selectedValueIndex || 0];
    } else {
      selected = this.props.selectedValue || 'select one';
    }
    var Typeval = Object.prototype.toString.call(this.props.data[0])

    if(['[object Array]', '[object Object]'].indexOf(Typeval) != -1){
        var slectedsetval = this.props.data.find(x => x.Val == selected).Type
        var Arraytype = 'Objectarray'
    } else {
        var slectedsetval = selected
        var Arraytype = 'Simplearray'
    }
    this.state = {
      modalVisible: false,
      selectedValue: selected,
      selected: slectedsetval,
      Arraytype : Arraytype
    };
  }

  componentWillReceiveProps(nextProps) {
    if ( this.props.data == null && nextProps.selectedValue !== this.state.selectedValue) {
      this.setState({
        selectedValue: nextProps.selectedValue,
      });
    }
  }

  pressItem = () => {
    this.setState({modalVisible:true});
  }

  valueChange = (data, index) => {
    if(this.state.Arraytype == 'Objectarray'){
      var selected = this.props.data.find(x => x.Val == data).Type
    } else {
      var selected = data
    }
    this.setState({modalVisible:false, selectedValue: data, selected: selected});
    this.props.onValueChange(data, index);
  }

  renderView = () => {
    return (
      <View style={[defaultStyles.container,this.props.style]}>
        <Text style={this.props.textStyle}>
          {this.state.selectedValue}
        </Text>
      </View>
    )
  }

  renderCollapseView = () => {
    return (
      <View style={this.props.collapseViewStyle}>
        <Picker 
              selectedValue={this.state.selectedValue}
              onValueChange={this.valueChange}>
              {(data && this.state.Arraytype == 'Objectarray') && data.map((d,t)=>
                  <Picker.Item style={pickerItemStyle} key={t} label={d.Type} value={d.Val} />
                )
              }
              {(data && this.state.Arraytype == 'Simplearray') && data.map((d,t)=>
                  <Picker.Item style={pickerItemStyle} key={t} label={d} value={d} />
                )
              }
            </Picker>
      </View>
    )
  }

  renderCollapsePicker() {
    return (
      <CollapseView 
        renderView={this.renderView}
        renderCollapseView={this.renderCollapseView}
      />
    )
  }

  renderModalPicker() {
    const { style, textStyle } = this.props;
    return (
    <View>
      <TouchableOpacity 
        activeOpacity={0.5}
        onPress={this.pressItem}
        style={[defaultStyles.container,style]}
      >
        <Text style={textStyle}>
          {this.state.selected}
        </Text>
      </TouchableOpacity>
    </View>
    )
  }

  render = () => {
    const { children, data, style, textStyle, pickerStyle, pickerItemStyle, disabled, mode} = this.props;
    return (
    <View>
      <Modal transparent visible={this.state.modalVisible} animationType='fade'>
        <TouchableOpacity activeOpacity={1} onPress={() => this.setState({modalVisible:false})} style={defaultStyles.overlay}>
          <View style={defaultStyles.picker}>
            <Picker 
              selectedValue={this.state.selectedValue}
              onValueChange={this.valueChange}>
              {(data && this.state.Arraytype == 'Objectarray') && data.map((d,t)=>
                  <Picker.Item style={pickerItemStyle} key={t} label={d.Type} value={d.Val} />
                )
              }
              {(data && this.state.Arraytype == 'Simplearray') && data.map((d,t)=>
                  <Picker.Item style={pickerItemStyle} key={t} label={d} value={d} />
                )
              }
            </Picker>
          </View>
        </TouchableOpacity>
      </Modal>
      {mode!=='modal' ? this.renderCollapsePicker() : this.renderModalPicker()}
    </View>
    );
  }
}

const defaultStyles = StyleSheet.create({
  container: {
    padding: 5,
    minHeight: 40,
    borderTopWidth: 0.5,
    borderColor: '#ddd',
    backgroundColor: '#fff',
    justifyContent: 'center',
  },
  overlay: {
    flex: 1,
    width: null,
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0,0,0,0.5)'
  },
  picker: {
    padding: 10,
    borderTopWidth: 0.5,
    borderColor: '#aaa',
    backgroundColor: 'white'
  },
  picker2: {
    backgroundColor: 'white'
  }
});

IOSPicker.propTypes = propTypes;
IOSPicker.defaultProps = defaultProps;
export default IOSPicker;
  1. Just apply your array as

const Options = ['a','b','c','d','e','f']

or

const Options = [{'Type': 'Option 1', 'Val': '1'},{'Type': 'Option 2', 'Val': '2'},{'Type': 'Option 3', 'Val': '3'}]

Note : Array objects Type and Val should be same

<IOSPicker 
                    mode={'modal'}
                    data={Options}
                    selectedValue={this.state.selectedValue}
                    onValueChange={(itemValue, itemIndex) => this.change(itemValue)}
                     />

Hope it will help you all :-)