Home > Enterprise >  React Js - Material UI - Change Min Date as per previous selection
React Js - Material UI - Change Min Date as per previous selection

Time:10-27

I have 2 date pickers in material UI-

From Date -

<KeyboardDatePicker
 value={initialDateFrom}
 disableFuture={true}
onChange={handleFromDateChange}
>
</KeyboardDatePicker>

To Date -

<KeyboardDatePicker
 value={initialDateTo}
 disableFuture={true}
onChange={handleToDateChange}
>
</KeyboardDatePicker>

const [initialDateFrom , setInitialDateFrom]= useState<any>(null);
const [initialDateTo , setInitialDateTo]= useState<any>(null);

const handleFromDateChange =(event:any , value :any)=>{
  setInitialDateFrom(value)
}

const handleToDateChange =(event:any , value :any)=>{
  setInitialDateTo(value)
}

What I am trying to achieve -

If I select 11-Oct-2021 as From date , I want to disable all the previous dates in To Date date picker to 11-Oct-2021. To Date - Date picker should show only future dates from 11-Oct-2021.

What I tried -

minDate = {initialDateFrom} in To Date datepicker

value.minDate = initialDateFrom in handleFromDateChange

But this did not helped.

CodePudding user response:

You can try this approach, I have created one more state to handle minDate

const [initialDateFrom , setInitialDateFrom]= useState<any>(null);
const [minDate, setMinDate] = useState<any>(null);
const [initialDateTo , setInitialDateTo]= useState<any>(new Date());

const handleFromDateChange =(event:any , value :any)=>{
  setInitialDateFrom(new Date(value));
  setMinDate(new Date(value))
}

const handleToDateChange =(event:any , value :any)=>{
  setInitialDateTo(value)
}

<KeyboardDatePicker
 value={initialDateFrom}
 disableFuture={true}
 onChange={handleFromDateChange}
>
</KeyboardDatePicker>

<KeyboardDatePicker
 value={initialDateTo}
 minDate={minDate}
 onChange={handleToDateChange}
>
</KeyboardDatePicker>
  • Related