How to Create an Event in the FullCalendar Library
If you’re looking to add a calendar to one of your vanilla JavaScript or React apps, FullCalendar is a great choice for accomplishing simple tasks. For my React app called Unwind, I wanted to give users the ability to schedule times to practice breathing techniques to relax.
Installation
To install FullCalendar and the plugins I used, enter the following command into your terminal:
npm install @fullcalendar/core @fullcalendar/daygrid @fullcalendar/timegrid @fullcalendar/interaction
That installs the core package along with the daygrid, timeGrid, and interaction plugins. Since I used React, I also imported each plugin from the FullCalendar package into my Profile.js
component, where I planned to render the calendar.
Render FullCalendar
After importing each plugin, you can then set up how your calendar will display in the browser. To display the calendar, create a FullCalendar component with the props below:
The initialView will determine what the calendar looks like on first render. In this case, I chose to see the current month. The headerToolBar sets up three things:
- left: buttons to navigate back and forth (“previous” and “next”)
- center: depending on which view you select (month, week, day), it displays the title of the current month, the dates of the week, or the single day.
- right: buttons to toggle viewing between “month,” “week,” or “day.”
The aspectRatio and height props determine the size. I also placed the FullCalendar component inside a div, so I could position the calendar on the page how I wanted with CSS. That gave me this:
Create an Event
Now that we’ve successfully rendered a calendar on the page, we can schedule an event. Notice the new props I added below:
The select prop will give us the ability to select time on the weekly view using a callback function. The handleTimeSelection()
callback function will update state for the start
and end
times of the event.
They are initially set to empty strings (see below). We also change the filledIn
state to true, since the dates have been “filled in.”
Since filledIn
is now equal to true, we can conditionally render a scheduling form. It displays the selected times, a dropdown menu for a user to choose a favorite breathing technique to practice, and a submit button that sends a POST request to the backend.
That POST request creates a practice_time object, consisting of a title, user_id, start, and end time, in the database. The function then toggles the filledIn
state back to false.
Once we’ve created our new practice_time or “event,” we can fetch all practice times and filter for only the ones who match our current user. The final line of code below is what renders the event objects in the calendar.
events={this.state.practiceTimes}
Once we have that, our final result is:
I’m still working to customize it more. In the meantime, you can check out the docs below for some inspiration.
Resources: