React-nice-calendar is missing a year

313 Views Asked by At

I am using react-nice-calender in my application. The problem is that the year is missing from the calendar as you see in the image. How can I fix that!

The code :

 const [date, setDate] = useState();

   <DatePickerCalendar
          date={date}
          onDateChange={setDate}
          locale={enGB}
     />

enter image description here

2

There are 2 best solutions below

2
On

If you want to show the year you have to format the date with date-fns dependencie so I take the example from: https://reactnicedates.hernansartorio.com/

import React, { useState } from 'react'
import { format } from 'date-fns'
import { enGB } from 'date-fns/locale'
import { DatePickerCalendar } from 'react-nice-dates'
import 'react-nice-dates/build/style.css'
function DatePickerCalendarExample() {
  const [date, setDate] = useState()
  return (
    <div>
      <p>
        Selected date: {date ? format(date, 'dd MMM yyyy', { locale: enGB }) : 'none'}.
      </p>
      <DatePickerCalendar date={date} onDateChange={setDate} locale={enGB} />
    </div>
  )
}

Here you have a codesandbox: https://codesandbox.io/s/datepicker-default-example-0kn7i

If you are in the current year it wont appear:

2021(current year): Example 2021(current year)

2023: Example 2023

0
On

react-nice-calendar doesn't display the current year. I've struggled with the same issue and found an elegant workaround. It is possible to hide the month with CSS in the upper navigation and then add your own month.

  1. Hide the built-in month:
.nice-dates-navigation_current {
  display: none;
}
  1. Add your own month and year with proper formatting and styling
<p className="calendar__current-date"> 
    {selectedDate.month}
</p>
<Calendar
    locale={enGB}
    month={selectedDate.date}
    onMonthChange={handleMonthChange}
/>
  1. Finally manage the state of the Calendar
  import { format } from 'date-fns'
 
  ...

  const [selectedDate, setSelectedDate] = useState<{
    date: Date
    month: string
  }>({
    date: new Date(),
    month: format(new Date(), 'MMMM yyyy', { locale: enGB })
  })

...

  const handleMonthChange = (date: any) => setSelectedDate({
    date,
    month: format(date, 'MMMM yyyy', { locale: enGB })
  })