1
votes

I am using DatePicker as a component to my Field from redux form. Right now each time I focus on the field the date picker opens. I cannot write the date to the input from the keyboadrd on my own (or paste it). I would like to combine both - enable user to paste/input the date from keyboard or pick it from date picker... How can I achieve this ?

import { Field, reduxForm } from 'redux-form';
import { DatePicker } from 'redux-form-material-ui';

....

<Field
  name="dateOfBirth"
  type="text"
  component={DatePicker}
  fullWidth
  formatDate={formatDate}
/>
1

1 Answers

0
votes
  1. Create a field in your component's "state".
  2. Insert value attribute to your <Field>, equal to the value of the state field. Also set the value of your DatePicker equal to this state field.
  3. In onChange of your <Field> and in onChange of your DatePicker, call setState to update the value of that state field.
  4. Now DatePicker and <Field> both will see the state change and update the value inside them.

Search for "React controlled input" for more details. Here is an example.

Update 1

I have not tested the following code. You might have to make changes to convert string to moment and vice-versa. DatePicker tag will also change based on which DatePicker library you are using. But this pseudo code should give you an idea on how to approach the problem.

Basically I have a DatePicker and an input, both of which show the dob from the component's state. And when their values are changed, the onSomethingChange functions will update the state value, hence updating both the DatePicker and the input. Hope this helps.

this.state = {
  dob: moment(props.dob)
};

<DatePicker
    date={this.state.dob}
    onDateChange={this.onDateChange}
    ... other attributes
/>

<input
    type="text"
    value={this.state.dob}
    onChange={this.onInputDateChange}
    ... other attributes
/>

onDateChange = (dob) => {
    if (dob) {
      this.setState(() => ({ dob }));
    }
};

onInputDateChange = (e) => {
    const dob = e.target.value;
    if (dob) {
      this.setState(() => ({ dob }));
    }
};