Real Scenario-Based Questions on Lightning Web Components (LWC) – Part 2

Scenario-based questions are a powerful tool for learning and assessing your skills in a real-world context. They mimic the challenges you'll face as a Salesforce developer, making them an excellent way to prepare for interviews, certifications, or simply to deepen your understanding of LWCs.

In this blog, we're going to dive into the heart of LWC development by exploring real scenario-based questions. These questions are designed to test your practical knowledge of LWCs and to help you master this technology through hands-on problem-solving.

Let start the interview series on `Real Scenario Based Interview Questions on Lightning Web Components Part -2` (Between Interviewer & Candidate).

In this blog series, I have tried to cover all `LWC Scenario Based Interview Questions` which are often asked by Salesforce Developer in an interview.


LWC Scenario 1 : Lightning Message Service
Question: Develop a Lightning Web Component that communicates with another component using the Lightning Message Service.

Let's create two Lightning Web Components (LWCs) that communicate with each other using the Lightning Message Service in Salesforce. We'll create a sender component that sends a message, and a receiver component that listens for and displays the received message.

Sender Component (senderComponent):

• In the `senderComponent.html`, create an input field and a button to send a message.
• In the `senderComponent.js`, handle the input field value, and when the button is clicked, publish the message to a Lightning Message Service channel.





// senderComponent.js
import { LightningElement, track } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import MESSAGE_CHANNEL from '@salesforce/messageChannel/MyMessageChannel__c';

export default class SenderComponent extends LightningElement {
    @track message = '';

    handleChange(event) {
        this.message = event.target.value;
    }

    sendMessage() {
        // Publish the message to the Lightning Message Service
        const payload = { message: this.message };
        publish(this.messageContext, MESSAGE_CHANNEL, payload);
    }

    // Get the message context for the Lightning Message Service
    messageContext = MessageContext;
}

Receiver Component (receiverComponent):

• In the `receiverComponent.html`, create an area to display received messages.
• In the `receiverComponent.js`, subscribe to the same Lightning Message Service channel and handle incoming messages.





// receiverComponent.js
import { LightningElement, wire, track } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import MESSAGE_CHANNEL from '@salesforce/messageChannel/MyMessageChannel__c';

export default class ReceiverComponent extends LightningElement {
    @track receivedMessage = '';

    @wire(MessageContext)
    messageContext;

    subscription;

    connectedCallback() {
        // Subscribe to the message channel
        this.subscription = subscribe(
            this.messageContext,
            MESSAGE_CHANNEL,
            (message) => {
                // Handle the received message
                this.handleMessage(message);
            }
        );
    }

    handleMessage(message) {
        this.receivedMessage = message ? message.message : '';
    }

    disconnectedCallback() {
        // Unsubscribe from the message channel when the component is destroyed
        unsubscribe(this.subscription);
    }
}

Lightning Message Service Configuration

• Import the `publish` and `subscribe` methods from 'lightning/messageService'.
• Create a custom message channel. Make sure both sender and receiver components reference the same channel.

Explanation:

• We have two Lightning Web Components: `senderComponent` and `receiverComponent`.

• `senderComponent` has an input field where you can enter a message and a button to send the message. When you click the "Send Message" button, it publishes the message to the Lightning Message Service using the `publish` method.

• `receiverComponent` listens for messages on the same message channel using the `subscribe` method. When it receives a message, it updates the `receivedMessage` property, which is displayed in the component's UI.

Output:

When you add both components to a Lightning page and enter a message in the sender component and click "Send Message," the message will be sent to the Lightning Message Service and received by the receiver component. The receiver component will display the received message in its card title.

This way, you achieve communication between two Lightning Web Components using the Lightning Message Service, enabling you to create modular and flexible Salesforce applications.


LWC Scenario 2 : File Upload
Question: Create a Lightning Web Component that allows users to upload files and display a list of uploaded files.

 MIND IT !

The interviewer likely asked the candidate to create a Lightning Web Component (LWC) for uploading files and displaying a list of uploaded files for several reasons:

Real-World Scenario: This question presents a real-world scenario that developers often encounter when building applications. In many Salesforce projects, there is a need to allow users to upload files, such as documents or images, and display a list of those files for easy access.

Assessing LWC Skills: It evaluates the candidate's proficiency in working with Lightning Web Components, a key technology in Salesforce development. LWCs are widely used for building interactive and user-friendly interfaces.

Component Interaction: The question assesses the candidate's understanding of how to create multiple LWCs and have them interact with each other. In this case, the file upload component communicates with the file display component.

File Handling Knowledge: It checks the candidate's knowledge of how to handle file uploads within Salesforce. This includes configuring file formats, associating files with records (if necessary), and managing file URLs.

In summary, the question serves as a comprehensive test of a candidate's skills, from building user interfaces with LWCs to handling file uploads, data transformation, and component interaction. It reflects the practical challenges faced by Salesforce developers and their ability to provide solutions using LWCs and Salesforce platform features.


Candidate's Response:

1. Clarify Requirements:
"Before I start coding, may I please confirm some details:

• Are there any specific file formats we need to support for uploads?
• Should the uploaded files be associated with Salesforce records, or is this a general file upload feature?
• Are there any styling preferences for the file display? Is there a preferred layout?"

2. Outline the Approach:
• "To address this scenario, I'll create two Lightning Web Components: one for file upload and another for displaying uploaded files.
• For file uploads, I'll use the built-in lightning-file-upload component, which simplifies the process.
• To ensure communication between these components, I'll use custom events.
• Now, let's proceed with the code."

3. Create the File Upload Component (fileUploadComponent):
fileUploadComponent.html - The markup for the file upload component:




Explanation:

We use the lightning-file-upload component to provide a user-friendly file upload interface.
• `label:` Specifies the label for the file upload input.
• `name:` Provides a name for the file uploader.
• `accept:` Defines the accepted file formats. In this example, we accept files with extensions .jpg, .jpeg, .png, and .pdf.
• `record-id:` This is an optional attribute that allows you to associate uploaded files with a specific Salesforce record. If set, the uploaded files will be linked to that record.

• When files are uploaded, the `onuploadfinished` event handler (`handleUploadFinished`) is called.

fileUploadComponent.js - The JavaScript file for the file upload component:

// fileUploadComponent.js
import { LightningElement, api } from 'lwc';

export default class FileUploadComponent extends LightningElement {
    @api recordId; // The record where the uploaded files will be associated (optional)
    acceptedFormats = ['.jpg', '.jpeg', '.png', '.pdf']; // Accepted file formats

    handleUploadFinished(event) {
        // Get the uploaded files
        const uploadedFiles = event.detail.files;

        // Notify the parent component about the uploaded files
        const fileUploadEvent = new CustomEvent('fileupload', {
            detail: { files: uploadedFiles }
        });
        this.dispatchEvent(fileUploadEvent);
    }
}

Explanation:

• We use the `@api` decorator to expose the `recordId` property, which can be set by the parent component if needed.

• In the `handleUploadFinished` function, we get the uploaded files from the event object (`event.detail.files`).

• We then dispatch a custom event (`fileupload`) to notify the parent component about the uploaded files, passing the files as a detail of the event.


4. Create the File Display Component (fileListDisplayComponent):
This component is responsible for displaying the list of uploaded files.

fileListDisplayComponent.html - The markup for displaying the list of uploaded files:




Explanation:

• We define an HTML template to display the uploaded files. We use an `<ul> `element with a `<template for:each>` loop to iterate through the uploaded files and display them as list items with links.

• Each file is displayed with a link that points to the file's URL, which can be accessed via Salesforce Content Delivery.

fileListDisplayComponent.js - The JavaScript file for displaying the list of uploaded files:

// fileListDisplayComponent.js
import { LightningElement, api, track } from 'lwc';

export default class FileListDisplayComponent extends LightningElement {
    @api files; // List of uploaded files received from the parent component

    @track uploadedFiles = [];

    connectedCallback() {
        this.updateUploadedFiles();
    }

    updateUploadedFiles() {
        // Transform the uploaded files data for display
        this.uploadedFiles = this.files.map(file => ({
            id: file.documentId,
            name: file.fileName,
            url: `/sfc/servlet.shepherd/version/download/${file.documentId}`
        }));
    }
}

Explanation:

• We use the `@api` decorator to expose the `files` property, which is passed by the parent component and contains the list of uploaded files.

• In the `connectedCallback` lifecycle hook, we call the `updateUploadedFiles` method to transform the uploaded files data into a format suitable for display.

• The `updateUploadedFiles` method creates an array of objects with properties for the file's ID, name, and URL for easy rendering in the template.


5. Parent Component Integration (parentComponent):

parentComponent.html - The markup for the parent component that uses both file upload and file display components:




Explanation:

• We include the `fileUploadComponent` to allow file uploads. We can optionally set the `recordId` property if we want to associate uploaded files with a specific Salesforce record.

• We include the `fileListDisplayComponent` to display the list of uploaded files. We pass the `uploadedFiles` property to it.

parentComponent.js - The JavaScript file for the parent component:

// parentComponent.js
import { LightningElement, track } from 'lwc';

export default class ParentComponent extends LightningElement {
    @track uploadedFiles = [];
    recordId; // Set this to the relevant record Id if needed

    handleFileUpload(event) {
        // Get the uploaded files from the file upload component
        this.uploadedFiles = event.detail.files;
    }
}

Explanation:

• We use the `@track` decorator to declare a `uploadedFiles` property to store the list of uploaded files.

• In the `handleFileUpload` event handler, we receive the uploaded files from the `fileUploadComponent`. We update the `uploadedFiles` property with the received files.

Output:

Before Uploading Files

After Uploading Files

When you add the parentComponent to a Lightning page, you will see a file upload component where you can select and upload files. After uploading files, they will be displayed as a list of links under the "Uploaded Files" section.


LWC Scenario 3 : Custom Modal
Question: Create a Lightning Web Component that displays a custom modal for user interaction.

 MIND IT !

The interviewer might ask the candidate to create a Lightning Web Component that displays a custom modal for user interaction for several reasons:

1. Assess Component Development Skills: Creating a custom modal involves various aspects of component development, including HTML, CSS, JavaScript, event handling, and user interaction. It allows the interviewer to assess the candidate's overall competency in building Lightning Web Components.

2. UI/UX Understanding: The task assesses the candidate's understanding of creating a user-friendly interface with modal dialogs. Candidates must consider how to design and style the modal to provide a good user experience.

3. Event Handling: Implementing features like opening, closing, and interacting with the modal typically involves event handling. The interviewer can evaluate the candidate's ability to manage events within Lightning Web Components.

4. Communication Between Components: In some cases, this task can be part of a larger scenario where components need to communicate with each other. Creating a modal that can send data or events to a parent component demonstrates the candidate's ability to work with inter-component communication.

5. Functional Use Case: Modals are commonly used for various purposes, such as form submissions, confirmations, or displaying information. The task simulates a real-world scenario where modal dialogs are commonly used in web applications.

6. Customization and Reusability: The candidate may need to create a modular and reusable component that can be easily customized by changing the title, message, or other attributes. This assesses the candidate's ability to design flexible components.

7. CSS and Styling: The candidate's knowledge of CSS and styling techniques may be evaluated as they are required to style the modal component appropriately.

8. User Interaction: The task checks if the candidate can handle user interactions effectively, such as capturing user input, responding to button clicks, and providing feedback to the user.

9. Error Handling: Candidates may need to consider error handling scenarios, such as validating user input or handling unexpected events.

10. Best Practices: Creating a custom modal offers an opportunity to assess whether the candidate follows best practices in Lightning Web Component development, including using decorators, managing component state, and adhering to Salesforce design guidelines.

Overall, this task provides a comprehensive assessment of the candidate's technical skills, problem-solving abilities, and understanding of building user interfaces within the Lightning Web Component framework.

Answer:Creating a custom modal dialog in a Lightning Web Component (LWC) involves creating a component that encapsulates the modal's content and can be toggled on and off. In this example, we'll create a simple LWC that displays a custom modal for user interaction.

1. Create the Modal Component (modalLWC):

modalLWC.html - Markup for the modal component:




modalLWC.js - JavaScript for the modal component:

// modalLWC.js
import { LightningElement, api } from 'lwc';

export default class ModalLWC extends LightningElement {
    @api modalTitle = 'Modal Title';
    @api modalMessage = 'This is a custom modal.';
    @api showModal = false;

    get modalClass() {
        return this.showModal ? 'slds-modal slds-fade-in-open' : 'slds-modal';
    }

    closeModal() {
        this.showModal = false;
    }
}

modalLWC.css - Styles for the modal component (customize as needed):

/* modalLWC.css */
.slds-modal {
    display: none;
}

.slds-modal.slds-fade-in-open {
    display: block;
    position: fixed;
    z-index: 1001;
    width: 40%;
    top: 20%;
    left: 30%;
    background-color: rgba(0, 0, 0, 0.6);
    border-radius: 4px;
}

.modal-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0px 0px 16px 0px rgba(0, 0, 0, 0.3);
}

.modal-buttons {
    text-align: right;
    margin-top: 16px;
}

2. Create a Parent Component (parentComponent):

parentComponent.html - Markup for the parent component:




parentComponent.js - JavaScript for the parent component:

// parentComponent.js
import { LightningElement, track } from 'lwc';

export default class ParentComponent extends LightningElement {
    @track showModal = false;

    openModal() {
        this.showModal = true;
    }
}

Output:

When you add the `parentComponent` to a Lightning page, you'll see a button labeled "Open Modal." Clicking this button will open the custom modal dialog, and clicking the "Close" button within the modal will close it.

 Extra Knowledge !

Let's create another example of a Lightning Web Component (LWC) that displays a custom modal for user interaction. In this example, we'll create a modal that allows users to enter their name and displays a greeting message.

1. Create the Modal Component (modalLWC):

modalLWC.html - Markup for the modal component:




modalLWC.js - JavaScript for the modal component:

// modalLWC.js
import { LightningElement, api } from 'lwc';

export default class ModalLWC extends LightningElement {
    @api modalTitle = 'Modal Title';
    @api modalMessage = 'Please enter your name:';
    @api showModal = false;
    userName = '';

    get modalClass() {
        return this.showModal ? 'slds-modal slds-fade-in-open' : 'slds-modal';
    }

    closeModal() {
        this.showModal = false;
    }

    handleNameChange(event) {
        this.userName = event.target.value;
    }

    submitForm() {
        this.closeModal();
        const event = new CustomEvent('submit', {
            detail: { userName: this.userName }
        });
        this.dispatchEvent(event);
    }
}

• The JavaScript file defines the behavior of the modal component.

• It has several attributes marked with the `@api` decorator, making them accessible from the parent component:

• `modalTitle`: The title of the modal (default: "Modal Title").
• `modalMessage`: The message displayed in the modal (default: "Please enter your name:").
• `showModal`: A boolean attribute that controls the visibility of the modal.
• `userName`: Stores the user's name entered in the input field.

• The modalClass getter computes the CSS classes for the modal container based on the `showModal` attribute. When `showModal` is `true`, the modal is displayed with a fade-in effect.

• The `closeModal` method sets `showModal` to `false`, hiding the modal.

• The `handleNameChange` method updates the `userName` attribute as the user types in their name.

• The `submitForm` method dispatches a custom event called "submit" and sends the user's name as the event detail. This allows the parent component to capture and handle the submitted data.


2. Create a Parent Component (parentComponent):

parentComponent.html - Markup for the parent component:




parentComponent.js - JavaScript for the parent component:

// parentComponent.js
import { LightningElement, track } from 'lwc';

export default class ParentComponent extends LightningElement {
    @track showModal = false;
    greetingMessage = '';

    openModal() {
        this.showModal = true;
    }

    handleModalSubmit(event) {
        this.showModal = false;
        this.greetingMessage = event.detail.userName;
    }
}

The JavaScript file for the parent component defines two attributes:

• `showModal`: A boolean attribute to control the visibility of the modal.
• `greetingMessage`: Stores the greeting message to be displayed.

• The `openModal` method sets `showModal` to `true`, triggering the display of the modal.

• The `handleModalSubmit` method captures the user's name from the "submit" event and sets it as `greetingMessage`. It also hides the modal by setting `showModal` to `false`.


Output:

When you add the `parentComponent` to a Lightning page, you'll see a button labeled "Open Modal." Clicking this button will open the custom modal dialog, where you can enter your name. Upon clicking the "Submit" button within the modal, it will close, and a greeting message will be displayed, addressing you by name.

This example demonstrates how to create a custom modal in a Lightning Web Component that takes user input and triggers an event to communicate with the parent component.


LWC Scenario 4 : Local Storage
Question: Create a Lightning Web Component that allows users to store and retrieve data using browser's local storage.


In this scenario, the task is to create a Lightning Web Component (LWC) that enables users to store and retrieve data using the browser's local storage mechanism. Local storage is a web browser feature that allows web applications to store data persistently within the user's browser, even after the browser is closed. This can be useful for storing user preferences, settings, or other data that should persist between sessions.

Question Explanation:
The interviewer asks the candidate to create a specific LWC that deals with local storage for the following reasons:

1. Understanding Browser Features: This scenario assesses the candidate's knowledge of browser features and their ability to utilize them within Salesforce Lightning components.
2. Data Persistence: It tests the candidate's understanding of how to achieve data persistence on the client-side, which is essential for many web applications.
3. User Experience: Implementing local storage can improve the user experience by allowing users to retain their preferences and settings across different sessions.
4. Data Management: The candidate needs to demonstrate their ability to manage data effectively, including storing, retrieving, updating, and clearing data from local storage.
5. Error Handling: Handling scenarios where local storage is not available or when there are storage limits is an important aspect of this task.

In this scenario, we'll create a Lightning Web Component (LWC) that allows users to store and retrieve data using the browser's local storage. Local storage is a client-side storage mechanism that allows data to persist even after the browser is closed. This is useful for storing user preferences or other data that should be retained between sessions.

1. Create the LWC (localStorageComponent):

localStorageComponent.html - Markup for the LWC:




localStorageComponent.js - JavaScript for the LWC:

// localStorageComponent.js
import { LightningElement, track } from 'lwc';

export default class LocalStorageComponent extends LightningElement {
    @track inputText = '';
    @track storedData = '';

    // Function to handle input field change
    handleInputChange(event) {
        this.inputText = event.target.value;
    }

    // Function to store data in local storage
    handleStoreData() {
        // Check if local storage is supported
        if (typeof window.localStorage !== 'undefined') {
            // Store data in local storage
            localStorage.setItem('userInput', this.inputText);
        }
    }

    // Function to retrieve data from local storage
    handleRetrieveData() {
        // Check if local storage is supported
        if (typeof window.localStorage !== 'undefined') {
            // Retrieve data from local storage
            this.storedData = localStorage.getItem('userInput');
        }
    }

    // Function to clear data from local storage
    handleClearData() {
        // Check if local storage is supported
        if (typeof window.localStorage !== 'undefined') {
            // Clear data from local storage
            localStorage.removeItem('userInput');
            this.storedData = '';
        }
    }
}

In this example:

• The component has an input field (`inputText`) where the user can enter data.
• The `handleStoreData` function stores the input data in local storage when a button is clicked.
• The `handleRetrieveData` function retrieves data from local storage when another button is clicked and displays it.
• The `handleClearData` function clears the data from local storage and resets the displayed data.

localStorageComponent.css - Styles for the LWC (you can customize this as needed):

/* localStorageComponent.css */
.button-section {
    margin-top: 16px;
}

.result {
    margin-top: 16px;
    border: 1px solid #ccc;
    padding: 8px;
    background-color: #f2f2f2;
}

2. Output:

When you add the `localStorageComponent` to a Lightning page, you'll see the following elements:

• An input field labeled "Enter Text" where you can type some text.
• Three buttons: "Store Data" (to save the text in local storage), "Retrieve Data" (to fetch and display the stored data), and "Clear Data" (to remove the stored data from local storage).
• Below the buttons, if data is stored, it will display the stored data with the label "Stored Data."

Usage:

1. Enter some text in the input field.
2. Click "Store Data" to save the text in local storage.
3. Click "Retrieve Data" to display the stored data.
4. Click "Clear Data" to remove the stored data.

The LWC demonstrates how to interact with local storage to store, retrieve, and clear data, providing a practical way to persist user data on the client side.


LWC Scenario 5 : Dynamic Styling
Question: Build a Lightning Web Component that dynamically applies styles based on user input.


In this scenario, we will create a Lightning Web Component (LWC) that dynamically applies styles to an element based on user input. This scenario tests the candidate's ability to work with dynamic styling and user interaction in LWCs.

Question Explanation:
The interviewer asks the candidate to create an LWC that applies styles dynamically based on user input to assess the following skills:

1. Styling Techniques: Understanding of how to dynamically apply CSS styles to LWC elements.
2. User Interaction: Handling user input or actions to trigger style changes.
3. Component Attributes: Using component attributes to store and update style-related data.
4. Conditional Styling: Implementing conditional logic to determine which styles to apply.
5. Real-Time Feedback: Providing immediate visual feedback to users based on their actions.

Example Code (Implementation):

In this example, we'll create an LWC called `dynamicStyleComponent` that allows users to enter a color and set the background color of an element dynamically.

dynamicStyleComponent.html - Markup for the LWC:




• The `<template>` element is the root of the Lightning Web Component's markup.

• `<lightning-input>`: This is a Lightning Base Component used for user input. It has the following attributes:

• `label`: Sets the label for the input field.
• `value={userInput}`: Binds the input field's value to the `userInput` property, enabling two-way data binding.
• `onchange={handleInputChange}`: Specifies the `handleInputChange` function to be called when the input value changes.

• `<div class="output" style={computedStyle}></div>`: This `<div>` element is used to display the dynamically styled output. It has a class name of "output" for styling purposes, and its `style` attribute is bound to the `computedStyle` property, allowing dynamic styling.

dynamicStyleComponent.js - JavaScript for the LWC:

// dynamicStyleComponent.js
import { LightningElement, track } from 'lwc';

export default class DynamicStyleComponent extends LightningElement {
    @track userInput = '';
    @track computedStyle = '';

    // Function to handle input field change
    handleInputChange(event) {
        this.userInput = event.target.value;
        this.computeStyle();
    }

    // Function to compute and set the background color based on user input
    computeStyle() {
        // Parse user input as a color (e.g., 'red', '#FF5733', 'rgb(255, 87, 51)')
        const colorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$|^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/;

        if (this.userInput.match(colorRegex)) {
            this.computedStyle = `background-color: ${this.userInput};`;
        } else {
            this.computedStyle = ''; // Reset style if input is invalid
        }
    }
}

• `@track userInput`: This property stores the user's input (color value).

• `@track computedStyle`: This property stores the computed style that will be applied to the output `<div>`.

• `handleInputChange(event)`: This function is called when the input value changes. It updates `userInput` with the new value and calls `computeStyle()` to recalculate the style.

• `computeStyle()`: This function computes and sets the background color based on the user's input. It uses a regular expression (`colorRegex`) to validate the input. If the input is a valid color (hexadecimal or RGB format), it sets the `computedStyle` property with the appropriate CSS background-color value. If the input is invalid, it resets the style to an empty string, effectively removing any background color.


dynamicStyleComponent.css - Styles for the LWC (you can customize this as needed):

/* dynamicStyleComponent.css */
.output {
    width: 200px;
    height: 100px;
    border: 1px solid #ccc;
    text-align: center;
    padding: 20px;
}

• This CSS file defines styles for the output `<div>` with the class "output." It sets the width, height, border, text alignment, and padding to give the output element a visually appealing appearance.

Output:

When you add the dynamicStyleComponent to a Lightning page, you'll see the following elements:

• An input field labeled "Enter a Color" where you can type a color value (e.g., "red," "#FF5733," "rgb(255, 87, 51)").
• Below the input field, a `div` element with the class "output" whose background color dynamically changes based on the user's input.

Usage:

1. Enter a valid color value in the input field (e.g., "red," "#FF5733," "rgb(255, 87, 51)").
2. The `div` element's background color will change to match the user's input color.

Overall, this Lightning Web Component demonstrates how to apply dynamic styles based on user input, providing real-time feedback to users as they interact with the component.


LWC Scenario 6 : Responsive Design
Question: Develop a Lightning Web Component that adjusts its layout based on the device's screen size.


In this scenario, we will create a Lightning Web Component (LWC) that adapts its layout and design based on the device's screen size. Responsive design ensures that the user interface looks and functions well on various screen sizes, such as desktops, tablets, and mobile devices.

Question Explanation:
The interviewer asks the candidate to create an LWC that adjusts its layout based on the device's screen size. This question assesses the following skills:

1. CSS Media Queries: The candidate should know how to use CSS media queries to apply different styles based on screen size.
2. Adaptive Layout: The ability to design an adaptive layout that provides an optimal user experience on different devices.
3. Component Attributes: Understanding how to use component attributes and JavaScript logic to conditionally apply styles.

Example Code (Implementation):

In this example, we'll create an LWC called `responsiveLayoutComponent` that adjusts its layout for small screens and large screens.

responsiveLayoutComponent.html - Markup for the LWC:




responsiveLayoutComponent.js - JavaScript for the LWC:

// responsiveLayoutComponent.js
import { LightningElement, track, api } from 'lwc';

export default class ResponsiveLayoutComponent extends LightningElement {
    @track isSmallScreen = false;

    connectedCallback() {
        // Check the screen size and set isSmallScreen accordingly
        this.isSmallScreen = window.innerWidth <= 768; // Adjust the breakpoint as needed
        window.addEventListener('resize', this.handleResize.bind(this));
    }

    handleResize() {
        // Handle screen size changes
        this.isSmallScreen = window.innerWidth <= 768; // Adjust the breakpoint as needed
    }

    get contentClass() {
        return this.isSmallScreen ? 'small-screen' : 'large-screen';
    }
}

responsiveLayoutComponent.css - Styles for the LWC:

/* responsiveLayoutComponent.css */
.container {
    text-align: center;
}

.small-screen {
    background-color: #f2f2f2;
    padding: 20px;
}

.large-screen {
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 40px;
    border-radius: 4px;
    box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.2);
}

Output:

Responsive Design - Desktop View

Responsive Design - Mobile View

When you add the `responsiveLayoutComponent` to a Lightning page and view it on different screen sizes (e.g., desktop and mobile), you'll observe the following behavior:

• For small screens (width less than or equal to 768 pixels), the content will have a light gray background with less padding.
• For large screens, the content will have a white background with a border, more padding, rounded corners, and a subtle box shadow.

The layout adjusts automatically as you resize the browser window, thanks to the event listener for the `resize` event. This ensures a responsive design that accommodates various screen sizes.

By using CSS media queries and JavaScript to check the screen size, you can create Lightning Web Components that adapt to the user's device, providing an optimal user experience.


LWC Scenario 7 : Geolocation
Question: Develop a Lightning Web Component that uses the browser's geolocation API to display the user's current coordinates.


In this scenario, we will create a Lightning Web Component (LWC) that utilizes the browser's geolocation API to retrieve and display the user's current coordinates (latitude and longitude). Geolocation is often used in web applications to provide location-based services or information.

Question Explanation:
The interviewer asks the candidate to create an LWC that leverages the browser's geolocation API to display the user's current coordinates. This question assesses the following skills:

1. Geolocation API: The candidate should be familiar with the browser's geolocation API and how to use it within LWC.
2. Data Retrieval: The ability to retrieve geolocation data (latitude and longitude) from the browser's API.
3. Component State: Managing component state to store and display geolocation information.

Example Code (Implementation):

In this example, we'll create an LWC called `geolocationComponent` that displays the user's current coordinates.

geolocationComponent.html - Markup for the LWC:




geolocationComponent.js - JavaScript for the LWC:

// geolocationComponent.js
import { LightningElement, track } from 'lwc';

export default class GeolocationComponent extends LightningElement {
    @track latitude = '';
    @track longitude = '';
    @track error = '';

    connectedCallback() {
        // Check if geolocation is supported by the browser
        if ('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(
                this.handleSuccess.bind(this),
                this.handleError.bind(this)
            );
        } else {
            this.error = 'Geolocation is not supported by your browser.';
        }
    }

    handleSuccess(position) {
        // Extract latitude and longitude from the geolocation data
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
    }

    handleError(error) {
        // Handle geolocation errors
        this.error = `Error: ${error.message}`;
    }
}

geolocationComponent.css - Styles for the LWC (you can customize this as needed):

/* geolocationComponent.css */
.error {
    color: red;
    font-weight: bold;
}

Output:

When you add the `geolocationComponent` to a Lightning page and open it in a browser that supports geolocation, you'll see the following output:

• "Current Coordinates" is displayed along with the user's latitude and longitude.
• If there is an error (e.g., if the user denies geolocation access or if geolocation is not supported by the browser), the error message is displayed in red.

Usage:

1. When the LWC is loaded, it checks if geolocation is supported by the browser.
2. If geolocation is supported, it calls `navigator.geolocation.getCurrentPosition()` to retrieve the user's current position.
3. If successful, it displays the latitude and longitude. If there's an error, it displays an error message.

This LWC demonstrates how to use the geolocation API to retrieve and display the user's current coordinates, providing location-based information or services within a Lightning component.


LWC Scenario 8 : Integration with Apex
Question: Create a Lightning Web Component that retrieves data from an Apex method and displays it.


In this scenario, we will create a Lightning Web Component (LWC) that interacts with an Apex method to retrieve data from Salesforce and displays it. Integrating LWCs with Apex allows you to access and manipulate Salesforce data from your Lightning components.

Question Explanation:
The interviewer asks the candidate to create an LWC that retrieves data from an Apex method and displays it. This question assesses the following skills:

1. Apex Integration: The candidate should understand how to integrate LWCs with Apex by defining Apex methods, calling them from LWCs, and handling responses.
2. Component State: Managing component state to store and display data fetched from Apex.

Example Code (Implementation):

In this example, we'll create an LWC called apexIntegrationComponent that fetches a list of records from a custom Apex controller method and displays them.

apexIntegrationComponent.html - Markup for the LWC:




apexIntegrationComponent.js - JavaScript for the LWC:

// apexIntegrationComponent.js
import { LightningElement, track, wire } from 'lwc';
import getRecordsFromApex from '@salesforce/apex/CustomController.getRecords';

export default class ApexIntegrationComponent extends LightningElement {
    @track records = [];

    @wire(getRecordsFromApex)
    wiredRecords({ error, data }) {
        if (data) {
            // If data is available, update the records property
            this.records = data;
        } else if (error) {
            // If there's an error, log it to the console
            console.error(error);
        }
    }
}

CustomController.cls - Apex Controller:

// CustomController.cls
public with sharing class CustomController {
    @AuraEnabled(cacheable=true)
    public static List getRecords() {
        // Replace 'MyCustomObject__c' with your custom object's API name
        return [SELECT Id, Name FROM MyCustomObject__c LIMIT 5];
    }
}

Output:

When you add the `apexIntegrationComponent` to a Lightning page and view it, you'll see the following output:

• "Records fetched from Apex" is displayed along with a list of records (e.g., Names) retrieved from the `MyCustomObject__c` object using the Apex controller method.

Usage:

1. The LWC uses the `@wire` decorator to call the `getRecordsFromApex` Apex method when the component is initialized.
2. The `wiredRecords` function handles the response from Apex. If data is available, it updates the `records` property with the retrieved records. If there's an error, it logs the error to the console.

This LWC demonstrates how to integrate with Apex to retrieve and display data from Salesforce within a Lightning component.


LWC Scenario 9 : Dynamic Form Fields with Validation
Question: Build a Lightning Web Component that generates input fields dynamically and performs client-side validation.


In this scenario, we will create a Lightning Web Component (LWC) that generates input fields dynamically and performs client-side validation. Dynamic forms with validation are commonly used in web applications to collect user data efficiently.

Question Explanation:
The interviewer asks the candidate to create an LWC that generates input fields dynamically and performs client-side validation. This question assesses the following skills:

1. Dynamic UI Generation: The candidate should understand how to generate input fields dynamically based on component data.
2. Client-Side Validation: Implementing client-side validation logic to ensure data accuracy and user feedback.
3. Component State: Managing component state to store and validate user input.

Example Code (Implementation):

In this example, we'll create an LWC called dynamicFormComponent that generates input fields dynamically and validates user input.

dynamicFormComponent.html - Markup for the LWC:




dynamicFormComponent.js - JavaScript for the LWC:

// dynamicFormComponent.js
import { LightningElement, track } from 'lwc';

export default class DynamicFormComponent extends LightningElement {
    @track fields = [
        { id: 'field1', label: 'Name', type: 'text', value: '', required: true },
        { id: 'field2', label: 'Email', type: 'email', value: '', required: true, 
          pattern: '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}' },
        { id: 'field3', label: 'Phone', type: 'tel', value: '', required: false,
          pattern: '\\d{10}', error: 'Phone number must be 10 digits' }
    ];

    handleInputChange(event) {
        const fieldId = event.target.id;
        const inputValue = event.target.value;

        // Find the field by ID and update its value
        const fieldToUpdate = this.fields.find(field => field.id === fieldId);
        if (fieldToUpdate) {
            fieldToUpdate.value = inputValue;
            fieldToUpdate.error = '';
        }

        // Validate the field based on pattern and required attributes
        if (fieldToUpdate.required && !inputValue) {
            fieldToUpdate.error = 'This field is required.';
        } else if (fieldToUpdate.pattern && inputValue) {
            const regex = new RegExp(fieldToUpdate.pattern);
            if (!regex.test(inputValue)) {
                fieldToUpdate.error = 'Invalid input.';
            }
        }
    }
}

Output:

Email Validation

Phone Field Validation

When you add the dynamicFormComponent to a Lightning page, you'll see the following output:

• The component generates input fields dynamically based on the `fields` array, including Name, Email, and Phone fields.
• The Email field has a regular expression pattern for email validation, and the Phone field has a pattern and a custom error message for validation.
• User input is validated as they type, and error messages are displayed below the fields if validation fails.

Usage:

1. The `fields` array in the component's state defines the dynamic form fields with properties such as label, type, value, required, pattern, and error.
2. The `handleInputChange` function is called when input values change. It updates the corresponding field's value and performs client-side validation based on the required attribute and pattern attribute (if provided).

This LWC demonstrates how to create a dynamic form with client-side validation, providing real-time feedback to users as they interact with the form.

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.