Search code examples
reactjscalendardatasource

How to customize date item with circular border in react-calendar?


Currently, I'm using react-calendar for a custom styled calendar in my project. I want to customize each date item with a circular border like the image below.

enter image description here

My dataSources is

type SourceType = {
    title: string,
    startDate: Date,
    endDate: Date,
    color: 'red' | 'blue'
}

dataSources: SourceType[]

and React-Calendar component is

import Calendar from 'react-calendar'
...
const [selectedDate, setSelectedDate] = React.useState(new Date())
...
<Calendar
    view='month'
    onChange={setSelectedDate}
    value={selectedDate}
/>

Please share your solution.


Solution

  • You can use tileClassName property of react-calendar. Here is my solution:

      import moment from 'moment';
      ...
      <Calendar
        view='month'
        onChange={setSelectedDate}
        value={selectedDate}
        tileClassName={({ date, view }: CalendarTileProperties) => {
            let resClassName = ''
            if (dataSources.find(x => (moment(x.startDate).format("DD-MM-YYYY") === moment(date).format("DD-MM-YYYY")) && (x.color === 'red'))) {
                resClassName += ' red_item'
            }
            if (dataSources.find(x => (moment(x.startDate).format("DD-MM-YYYY") === moment(date).format("DD-MM-YYYY")) && (x.color === 'blue'))) {
                resClassName += ' blue_item'
            }
            return resClassName
        }}
      />
    

    and insert the following scss code:

    .calendar {
        .month-container {
            .day {
                .day-content {
                    padding: 3px 6px;
                    border-radius: 50%;
    
                    &.blue_item {
                        border: 2px solid blue;
                    }
    
                    &.red_item {
                        border: 2px solid red;
                    }
                }
            }
        }
    }