Component Context in LWC

In the world of Salesforce development, Lightning Web Components (LWC) have emerged as a powerful tool for building dynamic and responsive user interfaces. As developers dive deeper into the LWC framework, understanding the concept of Component Context becomes essential. Component Context refers to the environment and resources available to a Lightning web component, including the ability to load external assets, access custom labels, check user permissions, and more. In this blog post, we will explore various aspects of Component Context in LWC and learn how to leverage its capabilities to enhance the functionality and flexibility of our components.

In this topic, we will cover it out basic of component context used in LWC, here are given below.

  1. Loading Third-Party JS Files
  2. Loading Asset Files
  3. Accessing Custom Labels
  4. Checking User/Custom Permissions
  5. Getting Information About the Current User


Loading third-party JavaScript files in LWC

Lightning Web Components allow developers to integrate third-party JavaScript libraries into their components. By importing external JavaScript files using the `@salesforce/resourceUrl` module and the `loadScript` function from the `lightning/platformResourceLoader` module, developers can enhance the functionality of their components with additional features and capabilities.


 MIND IT !


  • To use external CSS or JS library, first you need to download js or css library.
  • Then upload into static resource
  • Import static resource into LWC Component

import RESOURCE_NAME from "@salesforce/resourceUrl/RESOURCE_NAME";

  • Import `loadStyle` (Used to access css file), `loadScript` (Used to access js file) methods from `lightning/platformResourceLoader`, Both methods create and return promises.

  • loadScript(self, fileUrl): Promise
  • loadStyle(self, fileUrl): Promise

self — A reference to the component. The value must be “this”.
fileUrl — A string that contains the path to the JavaScript/css file.


import { loadStyle, loadScript } from "lightning/platformResourceLoader";

  • If you want to call multiple methods at once then you can use “Promise.all()” and pass your method in Array form.
  • The `.then()` callback is invoked only after the load completes and only if no error occurs. In `then()` you can access js file methods.

loadScript(this, myLib + "/myLib.js").then(() => {
  let result = myLib.myFunction(2, 2);
});

Note :- To invoke the `platformResourceLoader` methods we use `renderedCallback()` or `connectedCallback()` Methods based on the requirement.


Let's explore how to load a third-party JavaScript file in an LWC with an example code and output.

Example Code:

Suppose we want to use the Moment.js library in our LWC to handle date and time manipulations. Here's how we can load the Moment.js library in our LWC component:

First, install the Moment.js library using npm or yarn:

npm install moment

1. Define Static Resources:

Now, define static resources in your Salesforce org. You can do this by navigating to Setup > Static Resources and creating new static resources with unique names and upload js or css file.


2. Create a new Lightning Web Component (e.g., myComponent)

In the LWC component's JavaScript file (e.g., myComponent.js), import the Moment.js library:

import { LightningElement } from 'lwc';
import momentjs from '@salesforce/resourceUrl/momentjs'; // Import the resource URL of the Moment.js library

export default class MyComponent extends LightningElement {
    renderedCallback() {
        Promise.all([
            // Load the Moment.js library dynamically
            importMomentJs(),
        ]).then(() => {
            // Moment.js is now loaded and available for use
            this.handleDate();
        }).catch(error => {
            // Handle any errors while loading the library
            console.error('Error loading Moment.js:', error);
        });
    }

    handleDate() {
        // Use Moment.js functionality
        const currentDate = moment().format('MMMM Do YYYY, h:mm:ss a');
        console.log('Current Date:', currentDate);
    }
}

// Function to dynamically load the Moment.js library
function importMomentJs() {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = momentjs; // Set the source of the script to the resource URL of Moment.js
        script.onload = resolve; // Resolve the promise when the script is loaded
        script.onerror = reject; // Reject the promise if there is an error loading the script
        document.head.appendChild(script); // Append the script element to the document head
    });
}

myComponent.html




In this example:

  • We import the resource URL of the Moment.js library using the `@salesforce/resourceUrl` directive.
  • We use a `renderedCallback()` lifecycle hook to dynamically load the Moment.js library when the component is rendered.
  • Inside the `importMomentJs()` function, we create a new script element, set its source to the resource URL of Moment.js, and append it to the document head.
  • Once the script is loaded, the `onload` event handler resolves the promise, indicating that Moment.js is now available for use.
  • We then call the `handleDate()` method to demonstrate using Moment.js functionality to format the current date and time.

Output:


When the LWC component is rendered, Moment.js will be dynamically loaded, and the current date and time will be logged to the console using Moment.js's formatting functionality.

By following this approach, developers can seamlessly integrate third-party JavaScript libraries into their LWCs, expanding the capabilities of their components and delivering richer user experiences.


Load Asset file in LWC

In addition to JavaScript files, LWC also supports the loading of asset files such as images, CSS files, and other static resources. By importing asset files using the `@salesforce/resourceUrl` module, developers can easily incorporate visual elements and styling into their components, enhancing the overall user experience.


To create an Asset file in Salesforce, follow these steps:

  1. Go to your Salesforce org and navigate to the App Launcher.
  2. In the App Launcher search bar, type "Files" and select it from the results.
  3. Inside the Files tab, navigate to the Libraries section and click on "Asset Files."
  4. Here, you can upload your Asset file by clicking on the "Upload Files" button and selecting the file from your local system.
  5. Once the file is uploaded, it will be available as an Asset file in your Salesforce org.


To check your Asset file after uploading:

  1. Go to the Setup menu by clicking on your user avatar and selecting "Setup."
  2. In the Quick Find box, type "Asset Files" and select it from the search results.
  3. You will see a list of all the Asset files that have been uploaded to your org. You can click on the file name to view its details and properties.


Following these steps, you can easily create, upload, and manage Asset files in Salesforce for use in your Lightning Web Components (LWCs) or other parts of your org.


Real Scenario: Incorporating Images from Content Assets in Lightning Web Components

In a Salesforce project, you're tasked with developing a Lightning web component (LWC) that displays product information along with images. Instead of hardcoding the image URLs directly into your component, you want to utilize Salesforce Content Assets to manage and retrieve these images dynamically.

Here's how you can achieve this using the `@salesforce/contentAssetUrl` scoped module:

1. Access Content Assets in LWC:

  • Import the `@salesforce/contentAssetUrl` scoped module in your LWC JS file.
  • Use the `@salesforce/contentAssetUrl` decorator to dynamically import the image URLs based on their names.

Example Code (LWC JS file):

//productDisplay.js
import { LightningElement } from 'lwc';
import SFDX_CLI_COMMANDS from '@salesforce/contentAssetUrl/sfdx_cli_setup'; 
import IMAGE from '@salesforce/contentAssetUrl/project_app_img'; // Import content asset URL

export default class ProductDisplay extends LightningElement {
  cliCommands = SFDX_CLI_COMMANDS
  imageUrl = IMAGE // Assign imported URL to image source
}

2. Use Dynamic Image URLs in LWC HTML:

  • In your LWC HTML file, bind the dynamic image URL to the `src` attribute of the `img` tag.

Example Code (LWC HTML file):




Output:


  • Below the card's footer, there will be a hyperlink labeled "here" to download the SFDX CLI Commands File.
  • When you view the Lightning web component, it will dynamically display the image fetched from the content asset using the imported URL.
  • This approach ensures that you can easily manage and update images in your Salesforce org's Content Assets without needing to modify the component code.

By leveraging Content Assets and the `@salesforce/contentAssetUrl` scoped module in this manner, you can efficiently handle images in your Lightning web components, ensuring flexibility and ease of maintenance in your Salesforce projects.


Access Custom Label in LWC

Accessing custom labels in Salesforce Lightning Web Components (LWC) allows developers to use predefined text or messages that can be easily updated without modifying the code. This enhances the flexibility and maintainability of LWCs by centralizing text strings and making them easily customizable.

 MIND IT !


  • Create custom label in org
  • Import labels from the `@salesforce/label` scoped module.

import labelName from "@salesforce/label/labelReference";

  • To access custom labels use `@salesforce/label/c.your_custom_label_name`

Here's how you can access custom labels in LWC with example code and output:

1. Define Custom Labels:

First, define custom labels in your Salesforce org. You can do this by navigating to Setup > Custom Labels and creating new custom labels with unique names and corresponding values.

Example:

Label Name: welcome_message
Label Value: Welcome to our application!

2. Access Custom Labels in LWC:

In your LWC JavaScript file, import the `@salesforce/label` scoped module and reference the custom label using the label name.

//customLabelExample.js
import { LightningElement } from 'lwc';
import WELCOME_MESSAGE from '@salesforce/label/c.welcome_message';

export default class CustomLabelExample extends LightningElement {
    welcomeMessage = WELCOME_MESSAGE;
}

3. Use Custom Labels in HTML Template:

In your LWC HTML template, use the custom label variable to display the label value.



Output:


When you deploy and run your LWC, the custom label value will be displayed in the UI.

By accessing custom labels in this way, you can easily manage and update text strings across your application without modifying the code, providing a more scalable and efficient development process.


Check User/Custom Permission in LWC

Lightning Web Components enable developers to check user permissions and custom permissions sets to control access to certain features or functionality within their components. By querying the `User` and `PermissionSet` objects using the `@salesforce/schema` module, developers can dynamically adjust the behavior of their components based on the user's profile and permissions.


 MIND IT !

  • Import Salesforce permissions from the `@salesforce/userPermission` and `@salesforce/customPermission` scoped modules.

import hasPermission from "@salesforce/userPermission/userPermissionName";
import hasPermission from "@salesforce/customPermission/customPermissionName";

  • It returns a Boolean value.
  • To check whether a user has a permission, import a static reference to the permission and evaluate whether its ‘true’ or ‘undefined’.

Checking user or custom permissions in a Lightning Web Component (LWC) is crucial for controlling access to certain functionality based on a user's profile or permission set. Here's how you can implement this feature with example code and potential output:

Example Code:

HTML Template (permissionCheckExample.html ):




JavaScript File (permissionCheckExample.js):

//permissionCheckExample.js
import { LightningElement } from 'lwc';
import USER_PERMISSION from '@salesforce/userPermission/ViewAllData'
import CUSTOM_PERMISSION from '@salesforce/customPermission/Custom_Permission_Demo'

export default class PermissionCheckExample extends LightningElement {
  get userPermission(){
    return USER_PERMISSION
    }
  get customPermission() {
    return CUSTOM_PERMISSION
  }
}

Output:


In the component's template, we conditionally render different messages based on whether the user has the custom permission or not.

  • If the user has the custom permission, the card will display "Yes!! you have Custom_Permission_Demo custom permission to current user."
  • If the user does not have the custom permission, the card will display "No!! you dont have Custom_Permission_Demo custom permission to current user."

By implementing permission checks in your LWCs, you can ensure that certain features or functionality are only accessible to users with the appropriate permissions, enhancing security and controlling access to sensitive data or actions.


Get Information about Current User

Understanding the context of the current user is crucial for building personalized and interactive experiences in LWC. Developers can retrieve information about the current user, such as their name, email, profile, and more, by querying the `User` object using the `@salesforce/schema` module. This allows for the customization of component behavior based on the user's identity and preferences.

  • To get information about the current user, use the `@salesforce/user` scoped module.

import property from "@salesforce/user/property";

Property

  • `Id`: The supported properties are Id, which is the user’s ID.
  • `isGuest`: which is a Boolean value indicating whether the user is a guest user.

Example:




//getCurrentUserInfo.js
import { LightningElement } from 'lwc';
import USER_ID from '@salesforce/user/Id'
import IS_GUEST from '@salesforce/user/isGuest'

export default class GetCurrentUserInfo extends LightningElement {
  userId = USER_ID;
  isGuest = IS_GUEST;

}

Output:


 MIND IT !

"Get Information about Current User" is a common requirement in Salesforce development, often necessary for implementing personalized user experiences or enforcing security measures based on user attributes. One real-time scenario where this is applicable is in a custom profile management system.


Real-Time Scenario

Scenario :

Let's consider a scenario where we have a custom Lightning web component (LWC) designed for users to view and update their profile information.

Here's how we can use "Get Information about Current User" in this scenario:

  1. Display User Information: When a user accesses the profile management component, we want to display their current information, such as username, email, role, and profile picture.
  2. Customized Experience: Depending on the user's profile or role, we might want to show or hide certain sections of the profile management interface. For example, administrators might have access to additional settings compared to standard users.
  3. Security Checks: We can use the current user's information to enforce security checks. For instance, certain sensitive actions, like changing the email address, might require additional verification if the user is not an administrator.

Now, let's illustrate this with example code and output:

userProfile.js

// userProfile.js
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import USER_ID from '@salesforce/user/Id';
import NAME_FIELD from '@salesforce/schema/User.Name';
import EMAIL_FIELD from '@salesforce/schema/User.Email';

export default class UserProfile extends LightningElement {
    userId = USER_ID;
    userName;
    userEmail;

    @wire(getRecord, {
        recordId: '$userId',
        fields: [NAME_FIELD, EMAIL_FIELD]
    })
    wireUser({ error, data }) {
        if (data) {
            this.userName = data.fields.Name.value;
            this.userEmail = data.fields.Email.value;
        } else if (error) {
            console.error('Error fetching user details:', error);
        }
    }
}

userProfile.html




In this example, the `userProfile` component fetches the current user's information using the `@salesforce/user/Id` import, which provides the current user's ID. It then uses `lightning/uiRecordApi` to fetch the user record based on the ID. The retrieved data includes the user's name and email, which are displayed in the component.

Output:


The output of this component will be a Lightning card titled "User Profile" displaying the current user's name and email. If there's an error fetching the user's details, it will be logged in the console for debugging purposes.


Conclusion:

Component Context plays a significant role in the development of Lightning Web Components, providing developers with access to a wide range of resources and capabilities. By leveraging the features discussed in this blog post, developers can create dynamic, responsive, and user-friendly components that meet the unique requirements of their Salesforce applications. As you continue your journey with LWC development, exploring and mastering the intricacies of Component Context will empower you to build powerful and intuitive user interfaces that drive productivity and success.

References:

  • Salesforce Developer Documentation
  • Lightning Web Components Developer Guide
  • Salesforce Trailhead Modules

“Stay tuned for more exciting LWC topics, and keep exploring the world of Lightning Web Components to become a Salesforce development pro.”

Happy coding with LWC!

Share This Post:

About The Author

Hey, my name is Saurabh Samir and I am Salesforce Developer. I have been helping to elevate your Lightning Web Components (LWC) Knowledge. Do comment below if you have any questions or feedback's.