React Native Picker Display Current Month

769 views Asked by At

I am using React Native Picker to display the list of month numbers.

I am trying to show the current month when loading the picker (in this case 02 (February)).

But, when loading the screen it always displays 01(January) instead of 02(February).

Another thing is that even though label shows 01(January), the picker value however remains as 02(February).

It would be really helpful if someone could solve this issue.

Here's the code snippet provided below:

    const currentDate = new Date();
    const currentMonth = currentDate.getMonth() + 1;
    
    
    export default class AdminNews extends Component {
    
    
      constructor(props) {
        super(props);
        this.state = {
          date: {
            month: currentMonth,
          },
        }
      }
    
    
      renderMonthPickerItem() {
        //this shows the currentMonth but it overlaps with the other pickerItems.
        //which means it shows currentMonth 02 two times
        // let pickers = [
        //   <Picker.Item
        //     label={currentMonth.toString().padStart(2, '0')}
        //     value={currentMonth.toString()}
        //     key={currentMonth} />
        // ];
        let pickers = [];
    
        for (let month = 1; month <= 12; month++) {
          pickers.push(
            <Picker.Item label={month.toString().padStart(2, '0')} value={month.toString()} key={month} />
          );
        }
    
        return pickers;
      }
    
    
      renderMonth() {
        return (
          <>
            <View><Text style={{ fontWeight: 'bold', color: 'grey' }}>Month:</Text></View>
            <View style={{ marginVertical: 1 }} />
            <View style={{ borderRadius: 5, elevation: 3, backgroundColor: '#FAFAFA' }}>
              <Picker
                mode="dropdown"
                selectedValue={this.state.date.month}
                onValueChange={(itemValue, itemIndex) => {
                  this.setState({
                    date: {
                      ...this.state.date,
                      month: itemValue
                    }
                  });
    
                  this.apiNews();
                }}
              >
                {this.renderMonthPickerItem()}
              </Picker>
            </View>
          </>
        );
      }


       render(){ return( ***other code*** ); }
    };

Screenshot:

When calling the api it takes the value of month 02 but on picker it shows month 01. screenshot

0

There are 0 answers