Wednesday, 22 July 2020

LWC Basics



The JavaScript file for a Lightning web component must include at least this code, where MyComponent is the name you assign your component class.

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
}
The export statement defines a class that extends the LightningElement class. As a best practice, the name of the class usually matches the file name of the JavaScript class, but it’s not a requirement.



Lightning Web Components uses modules (built-in modules were introduced in ECMAScript 6) to bundle core functionality and make it accessible to the JavaScript in your component file. The core module for Lightning web components is lwc.

Begin the module with the import statement and specify the functionality of the module that your component uses.

The import statement indicates the JavaScript uses the LightningElement functionality from the lwc module.

// import module elements
import { LightningElement} from 'lwc';
// declare class to expose the component
export default class App extends LightningElement {
    ready = false;
    // use lifecycle hook
    connectedCallback() {
        setTimeout(() => {
            this.ready = true;
        }, 3000);
    }
}
LightningElement is the base class for Lightning web components, which allows us to use connectedCallback().
The connectedCallback() method is one of our lifecycle hooks. You’ll learn more about lifecycle hooks in the next section. For now, know that the method is triggered when a component is inserted in the document object model (DOM). In this case, it starts the timer.
Lifecycle Hooks
Lightning Web Components provides methods that allow you to “hook” your code up to critical events in a component’s lifecycle. These events include when a component is:

  • Created
  • Added to the DOM
  • Rendered in the browser
  • Encountering errors
  • Removed from the DOM
Respond to any of these lifecycle events using callback methods. For example, the connectedCallback() is invoked when a component is inserted into the DOM. The disconnectedCallback() is invoked when a component is removed from the DOM.

In the JavaScript file we used to test our conditional rendering, we used the connectedCallback() method to automatically execute code when the component is inserted into the DOM. The code waits 3 seconds, then sets ready to true.

import { LightningElement } from 'lwc';
export default class App extends LightningElement {
   
    ready = false;
    connectedCallback() {
        setTimeout(() => {
            this.ready = true;
        }, 3000);
    }
}



Also, notice that we used the this keyword. Keyword usage should be familiar if you’ve written JavaScript,
and behaves just like it does in other environments. The this keyword in JavaScript refers to the top level of the current context. Here, the context is this class. The connectedCallback() method assigns the value for the top level ready variable. It’s a great example of how Lightning Web Components lets you bring JavaScript features into your development. You can find a link to good information about this in the Resources section.
We’re moving fast and you’ve been able to try out some things. In the next unit, we take a step back and talk more about the environment where the components live.
Decorators
Decorators are often used in JavaScript to modify the behavior of a property or function.
To use a decorator, import it from the lwc module and place it before the property or function.
import { LightningElement, api } from 'lwc';
export default class MyComponent extends LightningElement{
@api message;
}
You can import multiple decorators, but a single property or function can have only one decorator. For example, a property can’t have @api and @wire decorators.
Examples of Lightning Web Components decorators include:
@api: Marks a field as public. Public properties define the API for a component. An owner component that uses the component in its HTML markup can access the component’s public properties.
All public properties are reactive, which means that the framework observes the property for changes. When the property’s value changes, the framework reacts and rerenders the component.
All fields are reactive. If the value of a field changes and the field is used in a template—or in the getter of a property used in a template—the framework rerenders the component. You don’t need to decorate the field with @track.
@track: Tells the framework to observe changes to the properties of an object or to the elements of an array. If a change occurs, the framework rerenders the component.
Use @track only if a field contains an object or an array and if you want the framework to observe changes to the properties of the object or to the elements of the array. If you want to change the value of the whole property, you don’t need to use @track.

LWC Deployment from VS Code

Deploy Lightning Web Component Files


Prior to Deploying the Lightning Web components need Developer org.


Set up Developer Environment

we develop a Lightning web component using VS Code with the Salesforce extension. We deploy the files to an org and build an app to use your component.



We need the following developer tools

  1. Visual Studio Code with the Salesforce Extension Pack
  2. Salesforce CLI
  3. Dev Hub enabled org
  4. My Domain deployed to users in your Dev Hub enabled org

1.    Visual Studio Code with the Salesforce Extension Pack

VS code can be downloaded from here.

Install VS code into Machine 

2.    Salesforce CLI

Salesforce CLI can be downloaded from here.

On downloading Salesforce CLI, install  into your machine, Setup the Environment variables.


Set Up Lightning Web Component Files for Use in an Org

Step1:

On installing VS Code and Salesforce CLI into your Mahine,



Head over the installed VS code, and install the Salesforce Salesforce Extension Pack.
πŸ‘‡

Salesforce Extension Pack

If you successfully installed Salesforce CLI and set up its Environment Variable can step into next steps

Step2:

Create the Scratch Org, Prior to the scratch Org creation, should have developer org created and atleast one user should be available.

If not have any developer Org created, Create from here.

1.    In VS code, press  keys

πŸ‘‰CTRL +SHIFT +P

or

Hit over the Gear key
 
πŸ‘‡





πŸ‘‰Crate the Project by using above step >> SFDX: Create Project >> Enter >>Select Standard Project Template(Default) >> Enter the Project Name>> It will Ask the Workspace Location >> Select Create Project



On above steps after succesful creation of Creating the Project you end up with below 

πŸ‘‰




Next Step is to Authorize the developer org created  previosuly

πŸ‘‰



On head over the above step>> IT will popsup type for what type org is to Authorize
>> Select based on your choice of working>> enter alias >> hit enter

Now It will open the Login Page of Salesforce >> Enter the credential and >> Login
πŸ‘‰





Now Its time to create your Lightning web component

Hit Gear icon or CTRL + SHIFT + P
πŸ‘‰

Enter the Name of the Lightning Web Component

Use foloowing LWC bundles as an Example


HTML File

<template>
    <div>
        <div>Name: {name}</div>
        <div>Description: {description}</div>
        <lightning-badge label={material}></lightning-badge>
        <lightning-badge label={category}></lightning-badge>
        <div>Price: {price}</div>
        <div><img src={pictureUrl}/></div>
    </div>
</template>


Javascript File


import { LightningElement } from 'lwc';
export default class BikeCard extends LightningElement {
   name = 'Electra X4';
   description = 'A sweet bike built for comfort.';
   category = 'Mountain';
   material = 'Steel';
   price = '$2,700';
   pictureUrl = 'https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax4.jpg';
 }



XML File

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <!-- The apiVersion may need to be increased for the current release -->
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now We will deploy into the Dev Org
πŸ‘‰


Once you will deploy will end up with following
πŸ‘‰

The configuration file with the extension .js-meta.xml. 
This file provides metadata for Salesforce, including the design configuration for components 
intended for use in Lightning App Builder.

The files that make up a component, including the configuration file.






Reference: Trailhead Salesforce


Why LWC?

Why Lightning Web Components?

Modern browsers are based on web standards, and evolving standards are constantly improving what browsers can present to a user. We want you to be able to take advantage of these innovations.

Lightning Web Components uses core Web Components standards and provides only what’s necessary to perform well in browsers supported by Salesforce. Because it’s built on code that runs natively in browsers, Lightning Web Components is lightweight and delivers exceptional performance. Most of the code you write is standard JavaScript and HTML.

You’ll find it easier to:

  1. Find solutions in common places on the web.
  2. Find developers with necessary skills and experience.
  3. Use other developers’ experiences (even on other platforms).
  4. Develop faster.
  5. Utilize full encapsulation so components are more versatile.
Basic Example to create the LWC Component

HTML

<template>
    <input value={message}></input></template>

    <template> is Fundamental building block, It stores pieces of HTML


JAVASCRIPT


export default class App extends LightningElement {
  message = 'Hello SFDCBlogger';
}
import { LightningElement } from 'lwc';


CSS

input {
   color: green;}


The LWC bundle comes with same name in same folder!!.

Salesforce compiles your files and takes care of the boilerplate component construction for you automatically.



LWC Aura can work Together?

    -Yes

Aura components can contain Lightning web components (though not vice-versa). But a pure Lightning web components implementation provides full encapsulation and evolving adherence to common standards.

To develop Lightning web components efficiently
  • Dev Hub and Scratch Orgs
  • Salesforce Command Line Interface (CLI)
  • Lightning Component Library

Scratch Org >> Disposable >> Support for Development and Testing

Dev Hub >> Manages the scratch Orgs

Salesforce CLI Prvides run opertions for creating & configuring the scratch orgs and deploying components

CLI (Command Line Interface), Scratch Org & Dev Hub are part of Salesforce DX tools