Apply Dynamic Item Style To React FullCalender

Viewed 354

I have a React "FullCalendar" that renders many dates. But I want to customize each date entity with a custom color obtained from server.

I'm aware about passing a 'class' to "FullCalendar" date entries, but since the color is coming from server and can be dynamic, I may have to use some sort of inline styling.

I also read about custom view implementation and am interested in it. But I was not able to implement it. Also I'm worried about performance as I've 100+ dates loaded from the server in an instant when using a complex custom view for my case.

This is my code:

import React, { useEffect, useState } from 'react'
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'

export const Calender = ({ dates }) => {

    //State
    const [upcomingDates, setUpcomingDates] = useState([])

    //Init function
    const init = () => {
        let dts = [];
        for (let i = 0; i < dates.length; i++) {
            dts.push(
                {
                    title: dates[i].EventText,
                    date: dates[i].Event,
                    className: 'bg-dark calender-item',

                    customColor: dates[i].CustomHexColor
                }
            );
        }
        setUpcomingDates(dts);
    }

    //UseEffect
    useEffect(() => {
        init();
    }, [dates]);


    //Custom content
    function renderEventContent(eventInfo) {
        return (
            <div style={{ backgroundColor: eventInfo.event.customColor}}>
                <b>{eventInfo.timeText}</b>
                <i> {eventInfo.event.title}</i>
            </div>
        )
    }

    return (
        <div className="card card-calendar">
            <div className="card-body p-3">
                <FullCalendar
                    headerToolbar={{
                        left: 'prev,next today',
                        center: 'title'
                    }}
                    eventContent={renderEventContent}
                    allDayClassNames="calendar"
                    plugins={[dayGridPlugin]}
                    initialView="dayGridMonth"
                    weekends={true}
                    events={upcomingDates}
                />
            </div>
        </div>
    );
}

enter image description here

As per the server response, I can see 3 distinct HEX color values coming in response for EVENT A, B and C.

1 Answers

A fullCalendar event object has a color property directly, so you can simply specify that in the data you pass from the server to fullCalendar. You're not required to use classes, if that's too restrictive.

e.g.

{
  "title": "Some event",
  "start": "2021-10-20",
  "color": "#B92808"
}

You can use any format to specify the colour which is recognised by CSS.

There are also other colour properties you can use if you need more flexibility over the appearance - see https://fullcalendar.io/docs/event-parsing for details.

Related