Search code examples
react-nativereact-reduxtimepicker

TimePicker (react-native-simple-time-picker) not able to set initial Value


I am using TimePicker in react native (react-native-simple-time-picker) and I want to set an initial value 10:47 but I am unable to set. I use property hoursUnit and minutesUnit but its very strange that a zero is appended infront of the value. like for hours its showing "010".

  <TimePicker
  hoursUnit="0"
  selectedMinutes="0"
  onChange={(hours, minutes) => this.setState({ selectedHours: hours, 
  selectedMinutes: minutes })}
   />

If I set hoursUnit as 10 , value comes 010.

Here is the code that I tried so far:

constructor(props) { super(props); 

state = { selectedHours: 10, selectedMinutes: 47, } } 
render (){ 
    return( <TimePicker 
            selectedMinutes={this.selectedMinutes} 
            selectedHours={this.selectedHours} 
            onChange={(hours, minutes) => this.setState({ 
                 selectedHours: hours,  
                 selectedMinutes: minutes })} /> 
) }

Solution

  • You are having this issue because you confused selectedHours with hoursUnit (which is a string for the label of hours) and provided a string for selectedMinutes & selectedHours - according to the API the type supposed to be a number. Therefore the API concatenated it to '010', because '10' was your label and selectedHours defaults to 0 when not provided, hence '010'..

    In order to get hours and minutes from your state-prop, you need to declare a const in your render-statement: const { selectedHours, selectedMinutes } = this.state; (See below for example..).

    From the docs:

    enter image description here

    To set an initial value, i.E. 10:47 you can try:

    export default class App extends Component {
      state = {
        selectedHours: 10,
        selectedMinutes: 47,
      }
    
      render() {
        const { selectedHours, selectedMinutes } = this.state;
        return (
          <View style={styles.container}>
            <Text>{selectedHours}:{selectedMinutes}</Text>
            <TimePicker
              selectedHours={selectedHours}
              selectedMinutes={selectedMinutes}
              onChange={(hours, minutes) => this.setState({ selectedHours: hours, selectedMinutes: minutes })}
            />
          </View>
        );
      }