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

Saurabh Samir
11 min readOct 1, 2023

--

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.html -->
<template>
<lightning-card title="Sender Component">
<div class="slds-p-around_medium">
<lightning-input label="Message" value={message} onchange={handleChange}></lightning-input>
<lightning-button label="Send Message" onclick={sendMessage}></lightning-button>
</div>
</lightning-card>
</template>
// 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.html -->
<template>
<lightning-card title="Receiver Component">
<div class="slds-p-around_medium">
<p>{receivedMessage}</p>
</div>
</lightning-card>
</template>
// 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.

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:

<!-- fileUploadComponent.html -->
<template>
<div>
<lightning-file-upload
label="Upload Files"
name="fileUploader"
accept={acceptedFormats}
record-id={recordId}
onuploadfinished={handleUploadFinished}>
</lightning-file-upload>
</div>
</template>

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:

<!-- fileListDisplayComponent.html -->
<template>
<div>
<h2>Uploaded Files</h2>
<ul>
<template for:each={uploadedFiles} for:item="file">
<li key={file.id}>
<a href={file.url} target="_blank">{file.name}</a>
</li>
</template>
</ul>
</div>
</template>

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:

<!-- parentComponent.html -->
<template>
<div>
<c-file-upload-component
record-id={recordId}
onfileupload={handleFileUpload}>
</c-file-upload-component>

<c-file-list-display-component files={uploadedFiles}></c-file-list-display-component>
</div>
</template>

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.html -->
<template>
<div class="{modalClass}">
<div class="modal-content">
<h2>{modalTitle}</h2>
<p>{modalMessage}</p>
<div class="modal-buttons">
<lightning-button label="Close" onclick={closeModal}></lightning-button>
</div>
</div>
</div>
</template>

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.html -->
<template>
<div class="slds-m-around_medium">
<lightning-button label="Open Modal" onclick={openModal}></lightning-button>
<c-modal-lwc
modal-title="Custom Modal"
modal-message="This is a custom modal dialog."
show-modal={showModal}
></c-modal-lwc>
</div>
</template>

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.

For More Questions visit the link below:

--

--

Saurabh Samir

Engineer @Accenture | Salesforce Developer | Full Stack Developer