Search code examples
react-datepicker

Showing only days in React Datepicker calendar


I am trying to use React Datepicker in my React application. I am following this document - https://reactdatepicker.com/

I need a date picker which will only show 31 days.

Here is the simple code from the react-datepicker documents.

<DatePicker selected={dayPicker} onChange={(date) => setDayPicker(date)} dateFormat="yyy/MM/dd" isClearable={true}

/>

It shows the full calendar. How can I customize the calendar ? Is it possible to remove the header from the calendar and replace it with a text "Days" ?


Solution

  • Following code will give you date picker for current year with only Month in header. You just need to use renderCustomHeader property of DatePicker.

        const year = 2022; // can be provided externally
        const month = 2; // can be provided externally
        const date = 24; // can be provided externally
        
        const [startDate, setStartDate] = useState(new Date(year, month, date));
        const minDate = new Date(year, month, 1);
        const maxDate = new Date(year, month + 1 , 0);
        
        const renderDayContents = (day, date) => {
        if(date < minDate || date > maxDate){
          return <span></span>;
        }
        return <span>{date.getDate()}</span>;
      };
        
        return ( 
            <DatePicker
            selected = {startDate}
            minDate = {minDate}
            maxDate = {maxDate}
            onChange = {(date) => setStartDate(date)}
            renderCustomHeader = {() => <div></div>}
            renderDayContents = {renderDayContents}
            dateFormat = "dd"
            />
        );
    

    This is how it will look:

    enter image description here

    Explaination:

    1. We can create out customer header with the renderCustomHeader property of DatePicker.

    2. This functions returns JSX (kind of html) which has empty div as we don't want to show anything in header.

    3. Apart from renderCustomHeader property, we have set minDate and maxDate property of DatePicker to restrict it for current month.

    4. You need to copy above code in a component where you are using DatePicker.

    You can refer https://reactdatepicker.com/#example-custom-header to know more about custom header for DatePicker