javascriptreactjstypescriptreact-datepicker

Is there any way to change the month dropdown on react-datepicker to show number instead of the name itself?


So I have here

 <DatePicker
   selected={value?.toDate()}
   onChange={(date) => this.handleMonthChange(date)}
   inline
   showMonthYearPicker
   dateFormat={this.props.formatString}
   />

enter image description here

I want to achieve that instead of Jan. It will display 01, and so on for other months. Thank you


Solution

  • You will have to define a renderMonthContent method and pass it as a prop to your DatePicker.

    As the month variable is the month's index (and as such, January is 0 instead of 1) we increment by 1.

    Also, we add .toString().padStart(2, 0) to achieve the always-2-digit presentation you want.

    const Component = () => {
      const renderMonthContent = (month, shortMonth, longMonth) => {
        return <span>{(month+1).toString().padStart(2, 0)}</span>;
      };
      ...
    
      return (
        <DatePicker
           selected={value?.toDate()}
           onChange={(date) => this.handleMonthChange(date)}
           inline
           showMonthYearPicker
           dateFormat={this.props.formatString}
           renderMonthContent={renderMonthContent}
           />
        ...
      );
    };

    Results:

    datepicker example