This is my calendar component:
export default class DemoApp extends React.Component {
today = new Date();
calendarRef = createRef();
....
I have a render function:
render() {
const workMin = this.state.hours.map(item => item.startTime).sort().shift();
const workMax = this.state.hours.map(item => item.endTime).sort().pop();
this.getDateResult();
return (
<div className='demo-app'>
{this.renderSidebar()}
<div className='demo-app-main'>
<FullCalendar
ref={this.calendarRef}
plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
headerToolbar={{
left: 'prev,next today',
center: 'title'
}}
locale="hr"
initialView='timeGridWeek'
editable={true}
selectable={true}
selectMirror={true}
dayMaxEvents={true}
weekends={this.state.weekendsVisible}
initialEvents={INITIAL_EVENTS}
select={this.handleDateSelect}
eventContent={renderEventContent}
eventClick={this.handleEventClick}
eventsSet={this.handleEvents}
eventStartEditable={false}
slotMinTime={workMin}
slotMaxTime={workMax}
validRange={{
start: this.today
}}
events={this.state.morningBgEvent}
/>
</div>
</div>
)
}
And this is my function:
getDateResult() {
const calendarApi = this.calendarRef.current.getApi();
console.log(calendarApi.activeStart);
}
Error:
Cannot read properties of null (reading 'getApi')
I just want to console.log the start day of next week view.
Why get this error?
You define a ref for your calendar and passed it to the FullCalendar element which is correct so far. but you are getting the calendarRef value before assigning it to the FullCalendar.
this.getDateResult(); // getting ref before assinging
return (
<div className='demo-app'>
{this.renderSidebar()}
<div className='demo-app-main'>
<FullCalendar
ref={this.calendarRef} // assigning ref
Using componentDidMount will ensure you the FullCalendar get its ref and then calls the getDateResult method properly.
Try to call your getDateResult inside of react life cycle method. for example, if you want to get the result on the initial phase, call the getDateResult method inside of a componentDidMount.
componentDidMount() {
getDateResult()
}
Also, with functional component structure with hooks:
useEffect(() => {
getDateResult()
}, [])