Hello friends, today I will explain how to import third-party libraries in LWC (Lightning Web Component). Use a third-party library with interactive charts and graphs or one to reduce code complexity. Due to Salesforce’s security policy, third-party scripts cannot be directly imported into Lightning web components. In our example, I will use Flat Date Picker in range input. Because salesforce has no option for range date picker so we can achieve this by importing the Flat Picker library in the LWC component.
Also,check this: Lightning Message Service (LMS) in LWC
Key Highlights :
- you need to download a third-party library and upload it to a static resource.
- We can use a third-party library like charts, graphs, etc.
Import methods from platformResourceLoader module.
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
Process & Code :
Step 1: Download this zip link.
Step 2: Upload this zip file to Static Resource.
Step 3: Now we will do code.
flatPickerLWC.HTML :
<template>
<lightning-card title="Import third party libraries in LWC/ Flat Date Picker" icon-name="standard:event">
<div class="slds-p-horizontal_small" onclick={openDatePicker}>
<lightning-input type="text" label="Enter some text" class="flatpickr"></lightning-input>
</div>
</lightning-card>
</template>
flatPickerLWC.JS :
import {LightningElement, track} from 'lwc';
import flatpick from '@salesforce/resourceUrl/flatpickr';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
var flatpickdp ={};
export default class FlatPickerLWC extends LightningElement {
@track selectedDate;
datepickerInitialized = false;
renderedCallback(){
if(this.datepickerInitialized){
return;
}
this.datepickerInitialized = true;
Promise.all([
loadScript(this, flatpick + '/flatpickr.js'),
loadStyle(this,flatpick + '/flatpickr.min.css')
]).then(() => {
this.initDatepicker();
})
.catch(error => {
console.log({message: 'Error onloading',error});
});
}
initDatepicker(){
let self = this;
const dpDiv = this.template.querySelector('lightning-input.flatpickr');
flatpickdp = flatpickr(dpDiv,{
inline:false,
minDate: "today",
mode: "range",
onChange: function(selectedDates, dateStr, instance) {
self.getDateVal(dateStr);
console.log(selectedDates);
console.log(dateStr);
},
onOpen: [
function(selectedDates, dateStr, instance){
console.log(selectedDates);
console.log(dateStr);
},
function(selectedDates, dateStr, instance){
console.log(selectedDates);
console.log(dateStr);
}
],
onClose: function(selectedDates, dateStr, instance){
console.log(selectedDates);
console.log(dateStr);
}
});
}
openDatePicker(){
flatpickdp.open();
}
getDateVal(dateStr){
console.log(dateStr);
}
}