Date Picker With Navigation Arrows on Left & Right In Lightning Web Components (LWC)
Table of contents
๐ฎ Demo
๐ Code
datepickerWithNavButtons.html
<template>
<lightning-card hide-header="true">
<div class="slds-card__body slds-card__body_inner">
<div class="slds-grid">
<div class="slds-col slds-grow-none">
<lightning-button-icon icon-name="utility:chevronleft" alternative-text="Previous" title="Previous"
data-direction="Previous" onclick={changeDate}>
</lightning-button-icon>
</div>
<div class="slds-col slds-grow-none slds-p-horizontal_x-small">
<lightning-input type="date" variant="label-hidden" value={selectedDate}
onchange={handleDateChange}>
</lightning-input>
</div>
<div class="slds-col slds-grow-none">
<lightning-button-icon icon-name="utility:chevronright" alternative-text="Next" title="Next"
data-direction="Next" onclick={changeDate}>
</lightning-button-icon>
</div>
</div>
<div class="slds-m-top_small">
Selected Date โก๏ธ <lightning-formatted-date-time value={selectedDate}></lightning-formatted-date-time>
</div>
</div>
</lightning-card>
</template>
datepickerWithNavButtons.js
import { LightningElement, track } from 'lwc';
export default class DatepickerWithNavButtons extends LightningElement {
@track selectedDate;
connectedCallback() {
//set today's date as default value of the datepicker
this.setCalendarStartDate();
}
// Method to set the initial value for the selectedDate property
setCalendarStartDate() {
// Set the selectedDate to the current date in the datepicker's desired format
this.selectedDate = this.formatToDatePickerValue(new Date());
}
// Event handler for changing the date based on previous & next button clicks
changeDate(event){
// Extract the direction from the clicked button's data-direction attribute
let direction = event.currentTarget.dataset.direction;
// Create a new Date object based on the current selectedDate
let currentDate = new Date(this.selectedDate);
// Adjust the date based on the direction (Previous or Next)
if(direction == 'Previous'){
currentDate.setDate(currentDate.getDate() - 1);
} else if(direction == 'Next'){
currentDate.setDate(currentDate.getDate() + 1);
}
// Update the selectedDate with the adjusted date
this.selectedDate = this.formatToDatePickerValue(currentDate);
}
// Event handler for handling changes when the user manually changes a date
handleDateChange(event){
// Update the selectedDate with the value choosen by the user
this.selectedDate = event.currentTarget.value;
}
// Utility method to format a Date object to the desired date picker value format
formatToDatePickerValue(dateVal){
// Convert the Date object to a string in the format YYYY-MM-DD
return dateVal.toISOString().slice(0, 10);
}
}
๐งฉ Components Used
Lightning Input - Type Date - https://developer.salesforce.com/docs/component-library/bundle/lightning-input/example
Lightning Button Icon - https://developer.salesforce.com/docs/component-library/bundle/lightning-button-icon/example
ย