Real Scenario-Based Questions On Lightning Web Components (LWC) — Part 3

Saurabh Samir
11 min readOct 11, 2023

Welcome to the third part of our blog series, “Real Scenario-Based Questions on Lightning Web Components (LWC).” In this series, we explore practical scenarios and questions that you may encounter in Lightning Web Component interviews and real-world development. Whether you’re preparing for an LWC interview or looking to enhance your LWC skills, this series is designed to help you navigate various scenarios effectively.

In Part 1 and Part 2, we delved into scenarios such as record editing, dependent picklists, real-time notifications, communication between components, and more. Now, in Part 3, we’ll continue our journey by tackling new challenges and exploring additional LWC concepts.

What to Expect in Part 3:

In this installment of the series, we’ll cover a fresh set of scenarios and questions, each designed to test your knowledge and problem-solving abilities in Lightning Web Components. These scenarios will span a wide range of topics, including integration with external services, handling user interactions, responsive design, and data visualization.

Let’s dive right in and start exploring these real-world scenarios. By the end of this blog, you’ll have a better understanding of how to approach complex LWC challenges and showcase your expertise effectively in interviews and projects.

Scenario Sneak Peek:

Here’s a sneak peek at some of the scenarios we’ll be addressing in Part 3:

  1. Real-Time Data Updates: Learn how to implement real-time data updates in LWCs, ensuring that your users receive immediate notifications about critical updates or events without constantly refreshing the page. We’ll explore techniques like Platform Events and Lightning Message Service.
  2. Custom Pagination: Dive into the world of custom pagination components in LWCs. Build a component that efficiently displays large sets of data with pagination controls, providing users with a seamless browsing experience.
  3. Custom Event Handling: Discover advanced custom event handling patterns in LWCs. We’ll explore scenarios where you need to create and handle custom events between components to facilitate communication and data exchange.
  4. Custom Search Component: Build a highly customizable search component that allows users to search and filter data within your LWCs. You’ll learn how to create a versatile search interface for various data types.
  5. Custom Notifications: Develop a custom notification system to keep users informed about important updates or messages within your LWCs. We’ll explore different approaches to creating and displaying notifications.
  6. Custom Sorting: Explore custom sorting functionality for your data tables and lists in LWCs. Implement sorting options that empower users to organize data according to their preferences.

Stay tuned for detailed explanations, example code, and insights into each scenario. Whether you’re an LWC developer or preparing for an LWC interview, this blog series is your go-to resource for mastering Lightning Web Components.

LWC Scenario 1 : Real-Time Data Updates
Question: Build a Lightning Web Component that displays real-time updates from a data source.

In this scenario, we will create a Lightning Web Component (LWC) that displays real-time updates from a data source. Real-time data updates are crucial for applications that require live information, such as chat applications or live feeds.

Question Explanation:
The interviewer asks the candidate to create an LWC that displays real-time updates from a data source. This question assesses the following skills:

  1. Real-Time Data Handling: The candidate should understand how to handle real-time data updates, often involving components subscribing to data events or streams.
  2. Component State: Managing component state to update the UI in response to real-time data changes.

Example Code (Implementation):

In this example, we’ll create an LWC called `realTimeUpdatesComponent` that simulates real-time updates and displays them.

realTimeUpdatesComponent.html — Markup for the LWC:

<!-- realTimeUpdatesComponent.html -->
<template>
<div class="slds-m-around_medium">
<p>Real-Time Data Updates</p>
<ul>
<template for:each={updates} for:item="update">
<li key={update.id}>{update.message}</li>
</template>
</ul>
</div>
</template>
  • This section defines the component’s markup. It includes a title “Real-Time Data Updates” and an unordered list (`<ul>`) to display updates.
  • A Lightning Web Component (LWC) can use dynamic rendering with the `<template>` tag, which allows us to loop through the updates array and display each `update` as an `<li>` element.

realTimeUpdatesComponent.js — JavaScript for the LWC:

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

export default class RealTimeUpdatesComponent extends LightningElement {
@track updates = [];

// Simulate real-time data updates (for example, from a streaming API)
connectedCallback() {
this.startUpdates();
}

startUpdates() {
// Simulate real-time updates every 3 seconds
setInterval(() => {
this.updates = [...this.updates, { id: Date.now(), message: 'New update received.' }];
}, 3000);
}
}
  • This section defines the JavaScript logic for the component.
  • We import necessary modules like `LightningElement`, `track`, and `wire` to build the component.
  • `@track updates = [];`: This line defines a tracked property called `updates`, which is an empty array. Tracking allows changes to this property to trigger UI updates.
  • `connectedCallback()`: This lifecycle hook is called when the component is connected to the DOM. In this hook, we call the `startUpdates` function to begin simulating real-time updates.
  • `startUpdates()`: This function simulates real-time updates by using `setInterval`. It adds a new update to the `updates` array every 3 seconds. Each update is an object with a unique `id` (timestamp) and a message indicating “New update received.”

Output:

When you add the `realTimeUpdatesComponent` to a Lightning page and view it, you’ll observe the following behavior:

  • The component displays the title “Real-Time Data Updates.”
  • Below the title, it lists updates, with a new “New update received” message appearing every 3 seconds. These updates simulate real-time data updates.
  • The component continues to add new updates to the list at intervals, creating the effect of real-time data updates.

Usage:

  1. The `connectedCallback` function is called when the component is initialized. It starts the simulation of real-time updates by calling `startUpdates`.
  2. The `startUpdates` function uses `setInterval` to add a new update to the `updates` array every 3 seconds. This simulates real-time data updates received from a data source like a streaming API.

This LWC demonstrates how to handle real-time data updates and update the UI accordingly, providing a dynamic and interactive user experience.

LWC Scenario 2 : Custom Pagination
Question: Create a Lightning Web Component that provides custom pagination for a list of records.

In this scenario, we will create a Lightning Web Component (LWC) that offers custom pagination for a list of records. Custom pagination allows users to navigate through a large set of data by displaying a limited number of records per page and providing navigation controls.

Question Explanation:
The interviewer asks the candidate to create an LWC that implements custom pagination for a list of records. This question assesses the following skills:

  1. Data Management: Understanding how to manage and paginate a list of records efficiently.
  2. Component State: Managing component state to control which records are displayed and which page is currently active.
  3. User Interface (UI): Creating pagination controls to allow users to navigate through the records.

Example Code (Implementation):

In this example, we’ll create an LWC called customPaginationComponent that implements custom pagination for a list of records.

customPaginationComponent.html — Markup for the LWC:

<!-- customPaginationComponent.html -->
<template>
<div class="slds-m-around_medium">
<p>Custom Pagination Example</p>
<ul>
<template for:each={displayedRecords} for:item="record">
<li key={record.Id}>{record.Name}</li>
</template>
</ul>
<div class="pagination">
<button onclick={previousPage} disabled={currentPage === 1}>Previous</button>
<span>Page {currentPage} of {totalPages}</span>
<button onclick={nextPage} disabled={currentPage === totalPages}>Next</button>
</div>
</div>
</template>

This section defines the component’s markup (HTML). It includes the following elements:

  • A title “Custom Pagination Example” to indicate the purpose of the component.
  • An unordered list (`<ul>`) to display records. It uses a dynamic rendering template (`<template for:each>`) to loop through the `displayedRecords` array and create list items (`<li>`) for each record.
  • Pagination controls with “Previous” and “Next” buttons for navigating between pages. These buttons have `onclick` event handlers to trigger the `previousPage` and `nextPage` methods. The `disabled` attribute is used to disable the buttons when navigating to the first or last page.
  • A display for the current page number (`currentPage`) and the total number of pages (`totalPages`).

customPaginationComponent.js — JavaScript for the LWC:

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

export default class CustomPaginationComponent extends LightningElement {
@track records = []; // Your list of records
@track currentPage = 1;
pageSize = 5; // Number of records to display per page

// Computed property to get the currently displayed records based on the current page
get displayedRecords() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.records.slice(start, end);
}

// Computed property to calculate the total number of pages
get totalPages() {
return Math.ceil(this.records.length / this.pageSize);
}

previousPage() {
if (this.currentPage > 1) {
this.currentPage -= 1;
}
}

nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage += 1;
}
}
}

This section defines the JavaScript logic for the component:

  • `@track records = [];`: This line declares a tracked property called records, which represents the list of `records` to be paginated. You can populate this list with your actual data.
  • `@track currentPage = 1;`: The `currentPage` property represents the currently active page, initialized to the first page (page 1).
  • `pageSize = 5;`: The `pageSize` property determines how many records are displayed per page. In this example, it’s set to 5, but you can adjust it as needed.
  • `get displayedRecords() {…}`: This computed property calculates and returns the records to display based on the current page. It uses array slicing to extract a subset of records for the current page.
  • `get totalPages() {…}`: This computed property calculates and returns the total number of pages. It divides the total number of records by the page size and rounds up using `Math.ceil`.
  • `previousPage() {…}`: This method handles the “Previous” button click event. It decrements the currentPage by 1 if the `current page` is greater than 1.
  • `nextPage() {…}`: This method handles the “Next” button click event. It increments the currentPage by 1 if the `current page` is less than the total number of pages.

Output:

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

  • The component displays the title “Custom Pagination Example.”
  • It shows a list of records based on the current page, with each page displaying the number of records defined by `pageSize`.
  • Pagination controls include “Previous” and “Next” buttons. These buttons enable users to navigate between pages of records.
  • The component dynamically updates the displayed records and pagination controls as users click “Previous” or “Next.”

Usage:

  1. The `displayedRecords` computed property calculates the records to display based on the current page. It slices the `records` array to get a subset of records for the current page.
  2. The `totalPages` computed property calculates the total number of pages by dividing the total number of records by the page size.
  3. The `previousPage` and `nextPage` methods handle navigation between pages. They update the `currentPage` property while checking for boundaries (e.g., not allowing navigation to a page less than 1 or greater than the total number of pages).

This LWC provides custom pagination controls for a list of records, enhancing the user experience when dealing with large datasets.

LWC Scenario 3 : Custom Event Handling
Question: Build a Lightning Web Component that demonstrates custom event handling between parent and child components.

In this scenario, we will create a Lightning Web Component (LWC) that demonstrates custom event handling between parent and child components. Custom events allow communication between components, enabling data and information exchange.

Question Explanation:
The interviewer asks the candidate to build an LWC that showcases custom event handling. This question assesses the following skills:

  1. Custom Event Creation: Understanding how to create custom events to facilitate communication between components.
  2. Event Dispatching: Dispatching (sending) custom events from one component and listening for them in another component.
  3. Parent-Child Component Interaction: Demonstrating the interaction between a parent and child component through custom events.

Example Code (Implementation):

In this example, we’ll create a parent component (`parentComponent`) and a child component (`childComponent`) that communicate through custom events.

parentComponent.html — Markup for the Parent Component:

<!-- parentComponent.html -->
<template>
<div class="slds-m-around_medium">
<p>Parent Component</p>
<c-child-component oncustomclick={handleCustomClick}></c-child-component&t;
<p>Message from Child Component: {messageFromChild}</p>
</div>
</template>

This section defines the markup for the parent component. It includes the following elements:

  • A title “Parent Component” to indicate the purpose of the component.
  • A `<c-child-component>` tag representing the child component. This is where the child component will be rendered.
  • A paragraph that displays a message received from the child component. The message is bound to the `messageFromChild` property in the JavaScript file.

parentComponent.js — JavaScript for the Parent Component:

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

export default class ParentComponent extends LightningElement {
@track messageFromChild = '';

handleCustomClick(event) {
this.messageFromChild = event.detail.message;
}
}

In the JavaScript file for the parent component, we define the following:

  • `messageFromChild`: This is a tracked property used to store the message received from the child component.
  • `handleCustomClick(event)`: This method is an event handler that responds to the custom event named `customclick`. When the child component dispatches this event, it carries a message payload in the `detail` property. This method extracts the message and updates the `messageFromChild` property with it.

childComponent.html — Markup for the Child Component:

<!-- childComponent.html -->
<template>
<div class="slds-m-around_medium">
<p>Child Component</p>
<button onclick={sendCustomEvent}>Send Custom Event to Parent</button>
</div>
</template>

This section defines the markup for the child component. It includes the following elements:

  • A title “Child Component” to indicate the purpose of the component.
  • A button labeled “Send Custom Event to Parent.” When clicked, this button triggers the `sendCustomEvent` method.

childComponent.js — JavaScript for the Child Component:

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

export default class ChildComponent extends LightningElement {
@track message = 'Hello from Child!';

sendCustomEvent() {
const customEvent = new CustomEvent('customclick', {
detail: { message: this.message },
});
this.dispatchEvent(customEvent);
}
}

In the JavaScript file for the child component, we define the following:

  • `message`: This is a tracked property used to store the initial message, which is “Hello from Child!”
  • `sendCustomEvent()`: This method is invoked when the “Send Custom Event to Parent” button is clicked. It creates a custom event named `customclick` using `CustomEvent`. The event includes a `detail` property with a `message` payload from the message property. Finally, it dispatches the custom event using `this.dispatchEvent(customEvent)`.

Output:

→ The parent component is displayed with the title “Parent Component.”

→When you click the “Send Custom Event to Parent” button in the child component, it dispatches a custom event (`customclick`) with a message payload.

When you view the parent component in a Lightning page, here’s what happens:

  1. The parent component is displayed with the title “Parent Component.”
  2. Inside the parent component, the child component is rendered as a child element.
  3. The child component has its title, “Child Component,” and a button labeled “Send Custom Event to Parent.”
  4. When you click the button in the child component, it dispatches a custom event named `customclick` to the parent component.
  5. The parent component listens for this custom event and handles it using the `handleCustomClick` method. It extracts the message from the event payload and updates the `messageFromChild` property with the received message.
  6. The message sent from the child component, which is “Hello from Child!”, is displayed in the parent component below the paragraph “Message from Child Component.”

Usage:

This example demonstrates how to create custom events and use them for communication between parent and child components in LWC. Custom events enable components to exchange information and trigger actions based on user interactions or other events.

For More Questions visit the link below:

Thanks for reading ☺️

--

--

Saurabh Samir

Engineer @Accenture | Salesforce Developer | Full Stack Developer