Implement Flatpickr Datepicker in Lightning Components.

We are going to implement a simple flatpickr datepicker. You can find more the details of the datepicker from their site: https://flatpickr.js.org/. This is a lean component, and it doesn't depend on any libraries.

The Html file :

<template>
    <article class="slds-card" >
        <div class="flatpickr" lwc:dom="manual" onchange={handleChangeDate}></div>
    </article>
</template>

Because we allow the flatpickr to append the HTML/script, so we use lwc:dom="manual" to avoid the error. We can also use the onchange event to catch the value of date change.

The Javascript File:

import {LightningElement,wire,track} from 'lwc';
import flatpick from '@salesforce/resourceUrl/flatpick';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
var flatpickdp ={};
export default class DatePicker extends LightningElement {
    
    datepickerInitialized = false;
    renderedCallback(){
        if(this.datepickerInitialized){
            return;
        }
        this.datepickerInitialized = true;

        Promise.all([
            loadScript(this, flatpick + '/flatpickr.js'),
            loadStyle(this,flatpick + '/material_blue.min.css')
        ]).then(() => {
            this.intializeDatepicker();
        })
        .catch(error => {
            console.log({message: 'Error onloading',error});
        });
    } 
    intializeDatepicker(){
        const dpDiv = this.template.querySelector('div.flatpickr');
        flatpickdp =  flatpickr(dpDiv,{
            inline:true,
            minDate: "today",
            appendTo:dpDiv
        });
    }

    handleChangeDate(evt){
        evt.preventDefault();
        const sDate = {
            dateString : evt.target.value,
            dateJs : flatpickdp.selectedDates[0]
        };
        evt.preventDefault();
        const changeDate = new CustomEvent('datechanged',{detail:sDate});
        this.dispatchEvent(changeDate);
    }
}

We can implement the handleChangeDate when date change, then fire a datechanged event.

<c-datepicker ondatechanged={handleDateSelected}></c-datepicker>

You can find the code here: https://github.com/leeseifer/flatpickr_lwc_implementation

No Comments Yet.

Leave a comment