Rinsen S
Rinsen S

Reputation: 481

React Antd not able to get value from custom date picker

I am currently using custom datepicker to enter date in the format 'MMDD' or 'MMDDYY' and setting the value in state and using in the datepicker component as controlled component. But on submit of form the datepicker value is undefined.

Please find the code in the codesandbox and correct me on what i am doing wrong in this one.

https://codesandbox.io/s/damp-haze-mmj80

Upvotes: 0

Views: 4823

Answers (3)

eliram9
eliram9

Reputation: 49

This is what works for me with React Hooks, hope it will help.

const initialInfo = {email: "", registrationDate: ""}
const [infoData, setInfoData] = useState(initialInfo);

inside of the component...

<DatePicker defaultValue={moment(infoData?.dateDisplay, dateFormat)} />

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53874

Only had to add a componentDidMount cycle:

componentDidMount = () => {
  this.props.onChange(this.state.value.format('YYYY-MM-DD'));
};

handleOnChange = date => {
  if (!!date) {
    this.setState({ value: date });
    this.props.onChange(date.format('YYYY-MM-DD'));
  }
};

Edit friendly-pare-21zso

Upvotes: 2

tmdesigned
tmdesigned

Reputation: 2254

I've not used that library (antd), but looking at the docs for it, using that fieldDecorator adds two properties to the component -- onChange and value.

  {getFieldDecorator("date-picker")(<CustomDatePicker />)}

So now imagine CustomDatePicker has those two properties. Value will be the value of the form item, and onChange is expecting to be called as the onChange handler of a form input.

However, in your CustomDatePicker component you aren't doing anything with either of those. Instead, you're tracking the value (and updating it with a handler) locally to that component with local state.

Instead, you should use those two properties:

 class CustomDatePicker extends React.Component {
  state = {
    isOpen: false
  };

  render() {
    return (
      <DatePicker
        value={this.props.value}
        format={this.state.isOpen ? ["MMDD", "MMDDYY"] : "MM/DD/YY"}
        placeholder=" -- Select Date --"
        disabledDate={d => d && d > moment(Date.now())}
        onOpenChange={status => {
          this.setState({ isOpen: status });
        }}
        onChange={this.props.onChange}
      />
    );
  }
}

If you want to do any initial value logic, or validation, you'll do that at the form-level component -- the one that is controlling the state.

Upvotes: 1

Related Questions