2

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

3
  • 1
    You're probably looking for this reactdatepicker.com/#example-custom-month Commented Jul 7, 2023 at 8:10
  • Actually, I'm using it now, adding showMonthYearPicker on Datepicker, but want I want to achieve is the dropdown menu will show numbers instead of Jan, Feb, Mar, Apr, etc... Commented Jul 7, 2023 at 8:16
  • Ooh, sorry, I didn't see that part. My bad for not double-checking. Now I get it. Thanks, mate! such a help Commented Jul 7, 2023 at 8:31

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

It's a good idea to lift renderMonthContent out of Component if it does not depend on any states/props/hooks. Currently renderMonthContent is re-defined every time Component renders, which doesn't seem necessary. Other than that, good answer.
@3limin4t0r is right on that. I didn't consider it while answering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.