What are Lightning Web Components?
Lightning Web Components (LWC) are a UI framework used by Salesforce Developers to create customized pages and functions on the Salesforce platform. Without a third-party framework, LWCs use a standardized JavaScript framework, HTML, and CSS. These are reusable ‘building blocks’ that Salesforce Admins can use for a variety of use cases.
Lightning Web Components are rapidly becoming the “next big thing” for Salesforce Developers, particularly in front-end development. They’ve had a long history, so let’s see where they are now.
Lightning Web Components adheres to core Web Components standards and provides only what is required to perform well in Salesforce-supported browsers. Lightning Web Components is lightweight and performs exceptionally well because it is built on code that runs natively in browsers. The majority of your code is standard JavaScript and HTML.
System Setup for Lightning Web Components
SFDX CLI must be installed. Please check the SFDX version to be matched to 45.0.X on CLI
If it is not already installed, download and install the most recent version of Visual Studio Code.
Set up Visual Studio Code Salesforce Extension Pack enhancement
Install the Lightning Web Components Visual Studio Code extension.
Field Reactivity
Fields are responsive. When the value of a field changes and the field is used in a template or a getter of a property used in a template, the component redraws and displays the new value.
The firstName and lastName fields are defined by the component’s class. They are reactive, as are all fields as of Spring ’20. Because they are used in the getter of a template property (uppercasedFullName), the component redraws when their values change.
Public Proprity Reactivity
Public spaces are reactive. The component re-renders if the value of a public property changes.
Decorate a field with @api to expose a public property. A component’s API is defined by its public properties.
The c-todo-item component is defined by this JavaScript class and HTML template, where c is the namespace. The itemName property can be set by a component that consumes the c-todo-item component.
To conform to HTML standards, JavaScript property names are in camel case, whereas HTML attribute names are in kebab case (dash-separated). The item-name attribute in markup maps to the itemName JavaScript property of c-todo-item in todoApp.html.
Reactivity and Data Types
Changes to the internal values of these types of fields are tracked by Lightning Web Components:
- Primitive value
- Simple objects created with… and annotated with @track.
- Arrays formed with [] and annotated with @track
- @track is only used on private properties; for public properties, use @api.
- @wire is used to connect LWC to Salesforce Data.
- There are two fields in the wire result: data and error.
- It’s as simple as that to use wire to access an apex class. It is faster, and the code is easier to read.
How to work withSalesforce Data
Use Lightning Data Service-based Base Lightning Components.
- Lightning-record-form, lightning-record-edit-form, and lightning-record-view-form are the foundational Lightning components built on Lightning Data Service.
Make use of Lightning Data Service. Wire Adapters and Their Applications
- Use @wire to specify the getRecord Lightning Data Service wire adapter to access raw record data so that you can perform business logic or create a form that requires more customization than the LDS base components allow.
Apex should be used To.
- To work with objects that the User Interface API does not support, such as Task and Event.
- To perform tasks that the User Interface API does not support, such as loading a list of records based on criteria (for example, loading the first 200 Accounts with Amount > $1M).
- To carry out a transactional action. For example, you could create an Account and then an Opportunity to go with it. If either create fails, the transaction is aborted.
- To call a method directly rather than through a wire service. You may want to call a method imperatively in response to a button click, or you may want to delay loading until it is outside the critical path.
Lightning Data Service
Lightning Data Service records are cached and shared across components. If a page is made up of components that all display the same record, all components display the same version of the record.
Lightning Data Service goes to great lengths to ensure that code runs smoothly.
- Loads record data in stages.
- Results are cached on the client.
- When dependent Salesforce data and metadata change, the cache entries are invalidated.
- Bulkifies and dedupes requests to optimize server calls.
UI API responses also take into account CRUD access, field-level security settings, and sharing preferences. This means that the framework only shows records and fields that users have CRUD access to and FLS visibility for. All of these features are available by utilizing the Lightning Data Service wire adapters (lightning/ui*Api) and the components built on it.
lightning-record-form
Click here for Salesforce library example for Record view Form.
- The lightning-record-form is the simplest way to display a record. A record can be displayed in two ways.
1.1.view
Loads the form with output fields enabled for inline editing. Editable fields are marked with edit icons. When a user clicks an edit icon, all fields in the form become editable, and Submit and Cancel buttons appear.
1.2.Read-only - mode loads the form with only output fields. The form lacks edit icons as well as Submit and Cancel buttons.
- Set the mode attribute to “Edit” to edit a record.
- Leave out the record-id attribute when creating a record with lightning-record-form.
- Use your own record Id, or place the example in a record page to inherit it.
lightning-record-view-form
Click here for Salesforce library example for Record view Form.
- Use the lightning-record-view-form component to display a record with a custom field layout.
- Use lightning-output-field components to create the form fields.
- Individual field inclusion allows you to style a custom field layout using Lightning Design System utility classes such as the grid system.
Use the getRecord or getRecordUi wire adapters to render data in a custom user interface. Import these lightning/uiRecordApi functions.
lightning-record-edit-form
Click here for Salesforce library example for Record Edit Form.
- Use the lightning-record-edit-form component to provide a custom layout for your form fields.
- Enter the fields into lightning-input-field, which displays an input control based on the type of record field.
Lightning-record-edit-form, unlike lightning-record-form, does not have its own Cancel and Save buttons. - Include a lightning-button component that calls the reset() method to create your own Cancel button that resets the field values.
- Replace the record-id with your own, or use this example to inherit the record-id property from a contact record page.
- You can handle the following custom events with lightning-record-edit-form.
- Error:- When the form returns a server-side error, this event is fired.
- load:—This event is triggered when the form loads record data.
- Submit:-When the form submits changed record data, this event is fired.
- success:—Fired when the form submits changed record data.
lightning-datatable component
- Use the lightning-datatable component to display Salesforce data in a table.
- Inline editing is supported by the component, allowing you to update a field value without having to navigate to the record.
- Use the getListUi (Beta) wire adapter to load a list of records. Alternatively, use SOQL in an Apex method to select specific records.
- Each row is associated with a contact record thanks to the key-field attribute.
- The data attribute contains the information obtained via the wire service from an Apex method or a wire adapter.
- The column attribute maps columns to record fields and customizes column behavior.
- When a user makes changes to a cell, the updated value is saved in draft-values.
<template><divstyle=”height: 300px;”><lightning-datatablekey-field=”id”data={data}columns={columns}></lightning-datatable></div></template>
Wire Service To Get The Data
- Lightning web components use a reactive wire service to read Salesforce data.
- To specify a Lightning Data Service wire adapter,
- use @wire in the JavaScript class of a component.
- The wire adapter defines the data shape provided by the wire service in an immutable stream.
- The lightning/ui*Api modules contain the LDS wire adapters, which are built on User Interface API resources.
- Each wire adapter offers a unique set of Salesforce data and metadata, ranging from individual records and lists of records to object and layout schema.
- Make sure there isn’t an easier way to get the data before using an Apex method.
- Check to see if a base Lightning component, such as lightning-record-form, lightning-record-view-form, or lightning-record-edit-form, fits your needs.
- If they are insufficiently flexible, use a wire adapter such as getListUi or getRecordUi.
- Syntax: import apexMethodName from ‘@salesforce/apex/Namespace.Classname.apexMethodReference’;
- NB: When an Apex class name changes outside of the JavaScript source file, the class name in the JavaScript source file is automatically updated
- Changes to method and argument names are not reflected in the JavaScript source file.
- An Apex method must be static and either global or public in order to be exposed to a Lightning web component. Add the @AuraEnabled annotation to the method.
- These types of input and output are supported.
- Primitive—Boolean, Date, DateTime, Decimal, Double, Integer, Long, and String.
- sObject—both standard and customized sObjects are supported.
- Apex—a member of the Apex class. (This is usually a custom class.)
- A collection is a grouping of any of the other types.
- Annotate the Apex method with @AuraEnabled(cacheable=true) to cache the method results on the client and improve runtime performance.
- A method must only get data to set cacheable=true; it cannot mutate (change) data.
- Marking a method as cacheable improves the performance of your component by displaying cached data from client-side storage without requiring a server trip. If the cached data is no longer valid, the framework retrieves the most recent data from the server.
- Caching is particularly useful for users with high latency, slow, or unreliable connections.
- You must set cacheable=true when using @wire to call an Apex method.
- The JavaScript code of the component imports the Apex method and calls it via the wire service. The wire service either populates the contacts.data property with a list of contacts or returns an error to the contacts.error property.
Calling out via wire service
- Define an Apex method that returns a Continuation object to create a long-running callout.
- In the continuationMethod property of the Continuation object, specify an Apex callback method to be invoked after the callout completes.
- Set the data to pass to the callback method in the Continuation object’s state property.
- Because the state property has an Object type, you can pass in any data type supported by Apex.
- In the Apex callback, write the logic. Labels—A list of labels, one for each request in the continuation, when all of the callouts set in the Continuation object have completed. These labels are generated automatically.
- state—The state that you specify in your Continuation object’s state property.
- HttpResponse response = Continuation.getResponse(labels[0]); for example
Event Communication
- Create and dispatch events in the JavaScript class of a component.
- Use the CustomEvent() constructor to create an event.
- Call the EventTarget.dispatchEvent() method to send an event.
- The only required parameter for the CustomEvent() constructor is a string indicating the event type.
- When you create an event as a component author, you name the event type. Your event type can be any string.
- It is, however, recommended that you follow the DOM event standard.
- There are no uppercase letters.
- There are no spaces.
- To separate words, use underscores.Because inline event handler names must begin with the string on, do not prefix your event name with the string on.
- The markup for your event would be c-my-component ononmessage=handleMessage> if it is called onmessage.
- Take note of the confusing doubled word onon.
Event Handling
- Listening for events can be done declaratively from the component’s HTML template or programmatically using an imperative JavaScript API.
- It is preferable to listen from the HTML template because it reduces the amount of code you must write. Define methods in the component’s JavaScript class to handle events.
- Keep an eye on the changes in the input field.
- Use the onchange event to listen for changes from an element in your template that accepts input, such as a text field (input> or lightning-input>).
Use the lwc method to communicate.
With the help of aura:method>, we can call the method of the Child Component from the Parent Component in the Aura framework (please see this post for more information on aura:method in aura).
We can do the same in LWC. Aura Methods in LWC are now JavaScript Methods.
Ex:
In JS Child Component:
@api
this.Message = strString.toUpperCase(); changeMessage(strString)
This.template.querySelector(‘c-child-component’) in Parent Component JS.
changeMessage(event.target.value);
Interact with lightning components
- Lightning web components and Aura components can coexist in an app thanks to an interoperability layer.
- You can create new Lightning web components and incorporate them into apps that include Aura components.
- Alternatively, you can migrate iteratively on your own timetable by replacing individual Aura components in your app with Lightning web components.
- Composing Aura components from Lightning web components is possible, but not the other way around.
- Parents assign properties to their children in order to communicate down the hierarchy.
- Understanding facets and slots will help you decide when and how to nest a Lightning web component in an Aura component.
Create a local server for lwc.
- Local Development allows you to create, run, and test Lightning Web Components without having to deploy your code to your Salesforce org.
- Local Development is a Salesforce CLI plugin.
- This will eventually be included with the Salesforce CLI, but for the time being, you must install it by running the following command.
- Install @salesforce/lwc-dev-server sfdx plugins
- After installing the plugin, you can use the start command to launch the Local Development Server on your Salesforce project.
- It is important to note that you must be authorized into an org before starting the server in order to use the data proxy features.
- Details can be found in the full documentation.
- force:lightning:lwc:start sfdx
- Local Development displays errors in the browser along with details such as the exact error message, the file and line where the error occurred, as well as a code snippet and stack trace to help you quickly identify the error.
- Local Development has integration with real org data
- Click on this link to learn about the current limitations of the Local Server.