Ant design DatePicker in form
Asked Answered
F

2

5

I'm using DatePicker component from antd inside a form and want to change the default onChange and value of props in DatePicker but it is not working.

<Form.Item
  label='Test Label'
  name='startDate'
  getValueFromEvent={(onChange) => moment(onChange).format('YYYY-MM-DD')}
  getValueProps={(i) => moment(i)}
>
  <DatePicker format='YYYY-MM-DD' style={{ width: '100%' }} />
</Form.Item>

When I use DatePicker outside of the form it works:

<DatePicker value={moment()} style={{ width: '100%' }} />

Is this a problem with getValueProps prop?

Foursquare answered 23/3, 2022 at 22:12 Comment(0)
F
16

I fixed it!

In case that anyone has same issue:

you have to change getValueProps to something like this:

getValueProps={(i) => ({value: moment(i)})}
Foursquare answered 24/3, 2022 at 15:51 Comment(1)
The date can be undefined and moment(undefined) results in current date. This equals to setting the default value to current date. Use getValueProps={(i) => ({ value: i === undefined ? undefined : moment(i) })} instead.Quay
G
2

For Ant Form:

<Form.Item
        name="dateOfBirth"
        label={t('date_of_birth')}
        rules={[{ type: 'object', required: true, message: t('this_field_is_required') }]}
        defaultValue={moment(user.dateOfBirth)}
        getValueProps={(i) => ({ value: moment(i) })}
    >
        <DatePicker
            format='DD/MM/YYYY'
            placeholder='DD/MM/YYYY'
            allowClear={false}
        />
</Form.Item>
Garlinda answered 12/9, 2023 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.