0

I'm trying to add a trigger on my site when I pass an hour in the first field, the second field must not allow the user to add an hour that's before the hour of the first field and can't do it with onChange because I'm using unform library and I have to separate the datepicker input in a separate component.

Anybody can help me?

The first code is my function the exclude time in the past from the second field

const handleGetPastTimes = useCallback(() => {
    try {
      const formData = formRef.current?.getData() as FormProps;
      const allHours = Array.from({ length: 24 }, (_, hour) => {
        const currentDate = new Date();
        currentDate.setHours(hour);
        currentDate.setMinutes(0);
        currentDate.setSeconds(0);
        return currentDate;
      });

      const excludeTimes = formData.schedule.map((scheduleItem) => {
        return allHours.filter((hour) => isBefore(hour, scheduleItem.from));
      });

      setPastTimes(excludeTimes);
    } catch (err) {
      console.error('ERRo');
    }
}, []);

The second code is the datepicker component with unform library

import React, { useRef, useState, useEffect } from 'react';
import ReactDatePicker, { ReactDatePickerProps } from 'react-datepicker';
import { useField } from '@unform/core';
import 'react-datepicker/dist/react-datepicker.css';

import { Container, DatePickerContainer } from './styles';

interface Props extends Omit<ReactDatePickerProps, 'onChange'> {
  name: string;
  label?: string;
}
const DatePicker: React.FC<Props> = ({ name, label, ...rest }) => {
  const datepickerRef = useRef(null);
  const { fieldName, registerField, defaultValue } = useField(name);
  const [date, setDate] = useState(defaultValue || null);

  useEffect(() => {
    registerField({
      name: fieldName,
      ref: datepickerRef.current,
      path: 'props.selected',
      clearValue: (ref: any) => {
        ref.clear();
      },
    });
  }, [fieldName, registerField]);
  return (
    <Container>
      <label htmlFor="">{label}</label>
      <DatePickerContainer>
        <ReactDatePicker
          ref={datepickerRef}
          selected={date}
          onChange={setDate}
          {...rest}
        />
      </DatePickerContainer>
    </Container>
  );
};
export default DatePicker;

0 Answers0