A lightning web component (LWC), a new Salesforce module increasing in popularity, allows us to bundle HTML markup and CSS styles into custom HTML elements. However, to understand and utilize an LWC correctly, we need to understand the following:
- How to create a basic LWC
- Composition and communication with events in an LWC
- Reactivity in an LWC
How to Create a Basic Component
Component: HTML File
It must contain the root tag “<template>” and it should be saved as “<component>.html” like myComponent.html below.
Component: Configuration File
All LWC configuration settings are included in a metafile. For example, “<isExposed>” is set to true to expose the component in all orgs. We can define targets where we wanted to use our LWC using the “<target>” tag.
Composition and Communication
Nesting of component into one another is called composition of components. It makes it feasible to build complex apps.
In the example above, an “example-to-do-wrapper” is the parent component, while the “example-to-do-item” is the child component. Generally, the child component is named as the owner component and the parent component is called as a container component.
Communication Using Events
An LWC can create and dispatch events in custom events, which are events manually created by a developer. Generally, the child component tells the parent component that an event has occurred, and the parent component sends data for the child component.
Events Up, Properties Down
To create an event, use the “CustomEvent()” constructor. The parent component has a handler to respond to that event. The information can pass down from the parent component to the child component to another level using the “public” and “private” methods.
An owner component can:
- Set public properties
- Listen for events dispatched
A container component can:
- Read, but not change, public properties
- Call public methods
Reactivity in an LWC
Observing change in properties and values, and then render component is the reactivity of LWC. LWC has three decorators to add functionality to properties.
- @track – Private properties can be made reactive by using the @track decorator. These properties develop a data binding behind a scene and update the template on change value.
- @api – Use the @api decorator to define public properties in your component. Generally, values of these properties can be supplied by the parent component.
- @wire – To read Salesforce data, Lightning web components use a reactive wire service.
LWCs Will Continue to Grow in Popularity
LWCs are still new, but learning about them is the first step to using them. With the introduction of LWC Salesforce, there have been several opportunities for developers with any background to build and develop on the Salesforce platform. For more information or further questions, contact our experts today, and happy developing!