Amount
1 month ago
Consent
1 year ago
utils
1 year ago
Checkbox.tsx
1 year ago
Date.tsx
1 year ago
Email.tsx
1 year ago
File.tsx
1 year ago
Gateways.tsx
1 year ago
Hidden.tsx
2 years ago
Honeypot.tsx
1 year ago
MultiSelect.tsx
2 years ago
Password.tsx
2 years ago
Phone.tsx
1 year ago
Radio.tsx
2 years ago
Select.tsx
1 year ago
Text.tsx
1 year ago
TextArea.tsx
2 years ago
Url.tsx
2 years ago
Date.tsx
54 lines
| 1 | import DatePicker from 'react-datepicker'; |
| 2 | import {format, parse} from 'date-fns'; |
| 3 | |
| 4 | import {DateProps} from '@givewp/forms/propTypes'; |
| 5 | import 'react-datepicker/dist/react-datepicker.css'; |
| 6 | import styles from '../styles.module.scss'; |
| 7 | import {useEffect, useRef} from "react"; |
| 8 | |
| 9 | /** |
| 10 | * @since 4.3.2 manually focus the visible input when error is present. |
| 11 | * @since 4.3.0 add aria-required attribute. |
| 12 | */ |
| 13 | export default function Date({ |
| 14 | Label, |
| 15 | ErrorMessage, |
| 16 | description, |
| 17 | dateFormat = 'yyyy/mm/dd', |
| 18 | fieldError, |
| 19 | inputProps, |
| 20 | }: DateProps) { |
| 21 | const FieldDescription = window.givewp.form.templates.layouts.fieldDescription; |
| 22 | const {useFormContext, useWatch} = window.givewp.form.hooks; |
| 23 | const {setValue} = useFormContext(); |
| 24 | const value = useWatch({name: inputProps.name}); |
| 25 | |
| 26 | const ref = useRef(null); |
| 27 | |
| 28 | dateFormat = dateFormat.replace('mm', 'MM'); |
| 29 | |
| 30 | useEffect(() => { |
| 31 | if (fieldError && ref.current) { |
| 32 | ref.current.focus(); |
| 33 | } |
| 34 | }, [fieldError]); |
| 35 | |
| 36 | return ( |
| 37 | <label ref={ref} className={styles.dateField}> |
| 38 | <Label /> |
| 39 | {description && <FieldDescription description={description} />} |
| 40 | <input type="hidden" {...inputProps} /> |
| 41 | <DatePicker |
| 42 | id={inputProps.name} |
| 43 | ariaInvalid={fieldError ? 'true' : 'false'} |
| 44 | dateFormat={dateFormat} |
| 45 | selected={value ? parse(value, dateFormat, new window.Date()) : null} |
| 46 | onChange={(date) => setValue(inputProps.name, date ? format(date, dateFormat) : '')} |
| 47 | ariaRequired={inputProps['aria-required']} |
| 48 | /> |
| 49 | |
| 50 | <ErrorMessage /> |
| 51 | </label> |
| 52 | ); |
| 53 | } |
| 54 |