i'm new to ReactJs and i'm trying to class component of FullCalendar to a functional component i watched some tutorials but when i did it i keep getting this error
Uncaught TypeError: Cannot read properties of null (reading 'getApi')
and i searched for a functional component for the FullCalendar but i didn't find anything useful this is my class component:
import React from "react";
import FullCalendar from "@fullcalendar/react";
import './Fullcalendar.css'
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction"; // needed for dayClick
export default class DemoApp extends React.Component {
calendarComponentRef = React.createRef();
state = {
calendarWeekends: true,
calendarEvents: [
// initial event data
{ title: "Event Now", start: "2022-03-21", backgroundColor: "red" }
]
};
render() {
setTimeout(() => {
let calendarApi = this.calendarComponentRef.current.getApi();
calendarApi.gotoDate(this.props.date); // call a method on the Calendar object
});
return (
<div>
<div className="demo-app">
<div className="demo-app-calendar">
<FullCalendar
id="fullCalendar"
contentHeight={720}
firstDay={1}
defaultView="dayGridMonth"
plugins={[dayGridPlugin, interactionPlugin]}
ref={this.calendarComponentRef}
events={this.state.calendarEvents}
/>
</div>
</div>
</div>
);
}
}
and this is what i did to converted to a functional component:
import React, { useRef } from "react";
import FullCalendar from "@fullcalendar/react";
import './Fullcalendar.css'
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction"; // needed for dayClick
function Fullcalendar({date}) {
const calendarComponentRef = useRef(null);
setTimeout(() => {
let calendarApi = calendarComponentRef.current.getApi();
calendarApi.gotoDate(date);
});
return (
<div>
<div className="demo-app">
<div className="demo-app-calendar">
<FullCalendar
id="fullCalendar"
contentHeight={720}
firstDay={1}
defaultView="dayGridMonth"
plugins={[dayGridPlugin, interactionPlugin]}
ref={calendarComponentRef}
/>
</div>
</div>
</div>
)
}
export default Fullcalendar
i tried and i searched but i don't know what i have to do.
It seems that you are setting a timeout which has no time associated, so it will run immediately. It tries to get the calendar component, but that seems to be before you've even returned the calendar component from your function, so I would expect that the calendar object doesn't exist yet, which is why your code can't find it.
Also, all you're doing with that API object is immediately setting the calendar date, but that's something you can do directly within the calendar options, if you want the calendar to start at a specific date.
Why not simply add
initialDate={date}
to the options in the <FullCalendar section instead?