How can I disable any day in an HTML input where the date is selected?

158 Views Asked by At

I have a page in React where I use browser input. How can I block any calendar day I specify in the relevant input?

<input type="date" id="start" name="trip-start" value="2018-07-22"/>

I need to prevent the user from making selections on special days I specify.

I know that the calendar is limited by values ​​such as min-max, but what I want is not to disable the days in a date range. I want to disable and prevent a date from being selected directly from any day or year in the calendar.

1

There are 1 best solutions below

6
Rachmat On

You can use package like react-datepicker and exclude the dates you want to disabled. Because achieving similar functionality with the standard HTML input date field can be challenging, especially without the support of the min and max attributes

https://stackblitz.com/edit/vitejs-vite-x9poca?file=src%2FApp.jsx

import { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import './App.css';

function App() {
  const disabledDates = ['2023-12-05', '2023-12-10', '2023-12-15'];
  const today = new Date();

  const [selectedDate, setSelectedDate] = useState(today);

  return (
    <>
      <DatePicker
        selected={selectedDate}
        onChange={(date) => setSelectedDate(date)}
        excludeDates={disabledDates.map((date) => new Date(date))}
      />
    </>
  );
}

export default App;