Webster
Webster

Reputation: 1153

React Native doesn't show Datepicker from TextInput

I wonder if it's possible to show the datepicker modal when the TextInput being pressed.

I'm using TouchableWithoutFeedback and TextInput. It works well if I use Text, but when I use TextInput, the datepicker modal doesn't show up.

The reason why I'm using TextInput is because I want to use the underlineColorAndroid prop.

Here's the code

showPicker = async (stateKey, options) => {
    try {
      const newState = {};
      const { action, year, month, day } = await DatePickerAndroid.open(options);
      if (action === DatePickerAndroid.dismissedAction) {
        newState[stateKey + 'Text'] = 'dismissed';
      } else {
        const date = new Date(year, month, day);
        newState[stateKey + 'Text'] = date.toLocaleDateString();
        newState[stateKey + 'Date'] = date;
      }
      this.setState(newState);
    } catch ({ code, message }) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  };

<TouchableWithoutFeedback
            onPress={this.showPicker.bind(this, 'simple', { date: this.state.simpleDate })}
          >
            <TextInput
              placeholder="Where the event held*"
              onFocus={() => this.onFocus()}
              onFocus={() => this.onFocus()}
              style={{ 
                height: 60, backgroundColor: this.state.backgroundColor, color: this.state.color 
              }}
              value={this.state.simpleText}
            />
          </TouchableWithoutFeedback>

The objective is whenever I press / click the TextInput, it will pop the datepicker modal up and then I can pick the date from the modal.

Upvotes: 3

Views: 6503

Answers (1)

Nguy&#234;n Ho&#224;ng
Nguy&#234;n Ho&#224;ng

Reputation: 1053

You just need to call showPicker function in onFocus props of TextInput. Like that:

<TextInput onFocus = {this.showPicker.bind(this, 'simple', { date: this.state.simpleDate })}>

Forgive me if my thoughts do not fit with your objective.

Upvotes: 6

Related Questions