0

My original question was a "how do I get this to work" question. I found a solution to the problem, but I have no idea how that works! So changing this question to a "why does this work" question.

Original question I'm using FullCalendar with React. I want to call certain methods on the calendar after it's rendered, eg gotoDate, like in the answer to this question. However, I don't know how to 'get' the FullCalendar on the page and call those methods.

I'm trying to follow the documentation on this page, "Calendar API" section, but am having trouble. Here's what my code boils down to:

export default function CalendarArea({ }) {
    const calendarRef = React.createRef()

    ... lots of code / function definitions ...

    const eventClickHandler = event => {
        event.jsEvent.preventDefault();
        debugger; // <- place where I'm testing things
    }

    return (
        ...
        <FullCalendar
            ref={calendarRef}
            eventClick={ (e) => eventClickHandler(e) }
            ...
        />
)}

What I was expecting is that at the debugger above, I'd be able to access calendarRef or this.calendarRef and do something like calendarRef.gotoDate(...). I suspect I'm misunderstanding something about how this works though.

Update - why does this work?

This SO post is what gave me a workaround that works. I can roughly understand that the original problem was that ref wasn't defined yet when the debugger line fired because of some way useRef is tied into the rendering lifecycle of a React app.

So in short, this now works as expected:

export default function CalendarArea({ }) {
    const calendarRef = React.useRef();
    const handleref = r => {
        calendarRef.current = r;
    }

    ... lots of code / function definitions ...

    const eventClickHandler = event => {
        event.jsEvent.preventDefault();
        debugger; // <- place where I'm testing things
    }

    return (
        ...
        <FullCalendar
            ref={handleref}
            eventClick={ (e) => eventClickHandler(e) }
            ...
        />
)}

With this setup, at the debugger, I can now see a value for calendarRef.current and access the FullCalendar API as I wanted.

But my question is - why does this work? There are many SO posts where the poster did something like my original code and it seems like it worked, so I'm curious why in this case I need this extra handleref workaround.

Allen Y
  • 341
  • 1
  • 11
  • I believe the correct process is explained in the [documentation](https://fullcalendar.io/docs/react) - take a look at the section of that page called "Calendar API" – ADyson Oct 11 '22 at 10:13
  • I was trying to follow that documentation, yep. I think that's what my original question was showing. But it wasn't working. I just posted a big update after finding a workaround, but to be honest I don't understand why the workaround works, and would love help with understanding that! – Allen Y Oct 15 '22 at 01:43

0 Answers0