Visualforce to LWC: SelectList to lightning-combobox
The transformation from Visualforce to Lightning Web Components might not be easy, because change is never easy. But once you start, you’ll get addicted to Lightning, it’s faster and way much powerful. I decided to make a series on how to transform the tags developers used in Visualforce to LWC.
In this article I will be discussing how to transform the SelectList in your Visualforce page to it’s equivalent in a Lightning Component. SelectList is a visualforce tag used to display a list of options and allow a user to select one or multiple values from it.
Here’s an example of a SelectList that lets a user choose a country:
The equivalent to SelectList tag in lightning is the lightning-combobox. This is the tag you use if you want the same functionality but in a Lightning Web Component.
Here’s the same example but done with a Lightning Component instead of a Visualforce page.
Line 3–10: We use our lightning-combobox component to enable the user to make a selection from a list of options. We’ve also defined some attributes for our component so let’s see what each one represents.
Label: The text label displayed above our combobox.
Placeholder: It’s the text that appears in grey before any option is selected.
Value: This is where our selected value will be stored.
Options: This is the list of options that will be available for selection
Line 4–10: We define an array called countryOptions that contains the options that the user can select. Each option must have two attributes: label and value. Label is the text appearing to the user. Also notice that we pass this array to the options attribute in Line 9 of the HTML file.
Line 14–16: This change handler is called when a user chooses a specific option. It takes the event as a parameter and assigns the value in the option to a variable called selectedValue. This is where the process of capturing the option chosen happens.