Color picker in lwc

To implement a color picker in a Lightning Web Component (LWC), you can use an HTML input element with type="color". Here’s a basic example of how you can create a color picker in an LWC:

<template>
    <lightning-card title="Color Picker">
        <div class="slds-p-around_medium">
            <lightning-input type="color" label="Choose a color" value={selectedColor} onchange={handleChange}></lightning-input>
        </div>
        <div class="slds-p-around_medium" style="background-color: {selectedColor}; width: 100px; height: 100px;"></div>
    </lightning-card>
</template>
import { LightningElement, track } from 'lwc';

export default class ColorPicker extends LightningElement {
    @track selectedColor = '#ffffff';

    handleChange(event) {
        this.selectedColor = event.target.value;
    }
}

In this example:

  • We use a lightning-card component for the overall container.
  • Inside the card, we have a lightning-input component with type="color". This creates a color picker input field.
  • We bind the selectedColor variable to the value attribute of the input field, so changes in the color picker update this variable.
  • We also have a handleChange method that updates the selectedColor variable whenever the user selects a new color.

This is a basic example to get you started. Depending on your requirements, you may need to enhance this component further, such as adding validation, handling more complex color operations, or styling adjustments.

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply