Home > OS >  I want to disable end date picker before choosing start date picker in react js
I want to disable end date picker before choosing start date picker in react js

Time:06-16

Is it possible to disable the end date picker until the user enters the start date? Below I am sharing my code. Please tell me where I am doing wrong?

const startDate = new Date();    
<Controller control={control} name="start_date" render={({ field }) => (
    <DatePicker placeholderText="MM/dd/yyyy" dateFormat="MM/dd/yyyy"
    onChange={(date) => field.onChange(date)}  minDate={moment().toDate()}
    selected={field.value}
    id="start_dates"
    required={true}
    autoComplete='off'
    onKeyDown={(e) => {
    e.preventDefault();
    }} />)}/>
    
    <Controller control={control} name="end_date"  render={({ field }) => (
    <DatePicker dateFormat="MM/dd/yyyy"
    onChange={(date) => field.onChange(date)}  
    disabled={startDate=== ""? true: false}
    minDate={new Date(startDate)}
    selected={field.value}
    
    onKeyDown={(e) => {
    e.preventDefault(); }} />)}/>

CodePudding user response:

Create state variable dateStart.

In onChange event of startDate set its value, then disable endDate based on dateStart like this:

const [dateStart, setDateStart] = useState(null);

StartDate datepicker

<DatePicker placeholderText="MM/dd/yyyy" dateFormat="MM/dd/yyyy"
    onChange={(date) => field.onChange(date); setDateStart(date)}  
    minDate={moment().toDate()}
    selected={field.value}
    id="start_dates"
    required={true}
    autoComplete='off'
    onKeyDown={(e) => {
    e.preventDefault();
    }} />)}
 />

EndDate datepicker

<DatePicker dateFormat="MM/dd/yyyy"
    onChange={(date) => field.onChange(date)}  
    disabled={dateStart ? false : true}
    minDate={new Date(startDate)}
    selected={field.value}
    
    onKeyDown={(e) => {
    e.preventDefault(); }} />)}
/>

Working example

  • Related