crutch12

DateField.tsx

Oct 14th, 2021
572
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { DateField as BaseDateField, DateFieldProps as BaseDateFieldProps } from '@vtb/ui-kit3';
  2. import moment from 'moment';
  3. import React from 'react';
  4. import styled from 'styled-components';
  5.  
  6. const format = 'DD.MM.YYYY';
  7.  
  8. export type DateFieldProps = Omit<BaseDateFieldProps, 'value' | 'onChange'> & {
  9.   value: string | null;
  10.   onChange: (date: string | null) => any;
  11. };
  12.  
  13. const DateField: React.FC<DateFieldProps> = ({ value, onChange, ...props }) => {
  14.   const [innerValue, setInnerValue] = React.useState<string | null>(value);
  15.  
  16.   const onDateChange = React.useCallback(
  17.     (date: string) => {
  18.       setInnerValue(date);
  19.  
  20.       if (date === '__.__.____') {
  21.         return onChange(null);
  22.       }
  23.  
  24.       if (!date.includes('_')) {
  25.         if (moment(date, format).isValid()) {
  26.           onChange(moment(date, format).format());
  27.         }
  28.       }
  29.     },
  30.     [onChange],
  31.   );
  32.  
  33.   React.useEffect(() => {
  34.     setInnerValue(value ? moment(value).format(format) : '');
  35.   }, [value]);
  36.  
  37.   return (
  38.     <StyledDateField value={innerValue || ''} onChange={(e) => onDateChange(e.target.value)} dimension="m" {...props} />
  39.   );
  40. };
  41.  
  42. const StyledDateField = styled(BaseDateField)``;
  43.  
  44. export default DateField;
  45.  
RAW Paste Data