7-Step Ultimate Guide: LWC Custom Events to Empower Your LWC


What’s the Deal with LWC Custom Events?

Alright, imagine you have two people – one wants to share a message, and the other is eager to listen. In the web world, especially when using Salesforce’s Lightning Web Components (LWC), this is a lot like what we call “custom events.”

So, custom events are like special messages. They allow one piece of code (let’s call it the “child”) to send messages to another piece (we’ll call it the “parent”). It’s like the child saying, “Hey parent, look what I’ve got!” and the parent replying, “Got it, kiddo!”

Why Do Parents and Children Need to Talk in LWC?

Imagine you’re building a puzzle. Each piece (or component) has its role, but sometimes they need to talk to each other to see the full picture. This “talking” or communication can help in:

Sharing Info

The child might have some cool info that the parent needs.

Coordinating Looks

If the child changes its look, the parent might want to match it.

Making Things Interactive

It’s all about team effort! When one changes, the other reacts.

Custom events make this chat between the parent and child happen smoothly.

Setting up the Child Component

The child component is our little messenger. Let’s teach it how to send messages!

Making the Child’s Button (chile.html)

We’re going to create a button. When someone clicks this button, it’ll send our special message.

    <lightning-button variant="brand" label="Dispatch Event" onclick={handleLoad}></lightning-button>

It’s a simple button, but it’s got a job: when clicked, it’s gonna run a function called handleLoad.

Teaching the Child to Send Messages (chile.Js)

Here’s the child’s game plan. When the button is clicked, it’s gonna shout out its message!

import { LightningElement, track } from 'lwc';

export default class CustomEvent extends LightningElement {

    @track test = 'Hey parent, here's a message from your child!';

    handleLoad() {
        console.log('Button was clicked!');
        this.dispatchEvent(new CustomEvent('mycustomevent', { detail: this.test }));

See the handleLoad function? That’s where the magic happens. The child uses it to send its message, which says, “Hey parent, here’s a message from your child!”

With our child ready to send messages, next, we’ll set up the parent to listen and react to these messages. Cool, right?

Setting up the Parent Component

Okay, so our little messenger (the child component) is ready to shout out its messages. Now, we need our parent component to lend an ear and catch whatever the child is saying.

The Parent’s Listening Spot (parent.html)

Here’s a spot where the parent waits and listens. It’s like setting up a mailbox where the child can drop off its messages.

        <h2>A Message From My Child: </h2>  {msg}
        <c-save-pdf onmycustomevent={handleCustomEvent}></c-save-pdf>

This spot has a title “A Message From My Child” and a placeholder ({msg}) to show the child’s message. The onmycustomevent part? That’s the parent’s ear, always waiting for the child’s shout-out.

Teaching the Parent to Understand (parent.js)

Now, when the parent hears the child, it needs to understand and react. Let’s see how:

import { LightningElement, track } from 'lwc';

export default class SavePdf extends LightningElement {

    @track msg;

    handleCustomEvent(event) {
       console.log('I heard my child!');
       this.msg = event.detail;
       console.log('Here’s the full message: ' + JSON.stringify(event));

The handleCustomEvent function is like the parent’s brain. When the child sends a message, this function says, “I got it!” and then shows the message in the placeholder we set up earlier.

Walkthrough of the Custom Event Process

Let’s see the whole thing in action, step by step!

Before the Button Click

At first, everything’s calm. The parent is waiting, and there’s no message shown. It’s like the calm before a fun surprise.

The Button Click and the Message Sent

Now, someone comes along and clicks the button in the child component. It’s like ringing a doorbell! The child shouts out its message, hoping the parent will hear.

After the Button Click

Bingo! The parent hears the child’s shout-out and quickly grabs the message. Then, it proudly displays it for everyone to see. Mission accomplished!

And there we have it! The child sends its special messages, and the parent is all ears, catching every word. It’s teamwork at its finest, making our components interactive and alive!

Troubleshooting & Common Issues

Okay, so things don’t always go as planned, right? Sometimes, the child might be shouting out its messages, but the parent just isn’t hearing. Here’s what could be going wrong and how to fix it:

Missed Connections

Double-check the event name! If the child is shouting “Hey!” and the parent is listening for “Hello!”, they’ll miss each other.

Lost Messages

Sometimes, the message (or the data) from the child might not be getting through. Ensure the child is sending the message correctly and that the parent knows how to read it.

Silent Child

Is the button in the child component working? Make sure it’s correctly linked to the function that sends the message.

Overwhelmed Parent

Too many messages or events can overwhelm the parent. Ensure it’s set up to handle multiple messages or events gracefully.

If you’ve checked all these and still face issues, sometimes it’s a good idea to start fresh or ask a buddy for a second pair of eyes.


Before Child component Button Click

After Child component Button Click

lwc custom event on button click

Related Questions & Further Reading

Still curious or facing some head-scratchers? Don’t worry! There are tons of folks out there who’ve asked some great questions, and you might find your answers (or more inspiration) in their discussions:

How to dispatch an event between LWCs not in the same tree?
Have trouble creating and dispatching events in LWC?

And always remember, the Salesforce community is vast and supportive. Whenever you’re stuck, don’t hesitate to ask. Someone out there has probably faced the same issue and might have the perfect solution for you!

Frequently Asked Questions (FAQ)

What are custom events used for in LWC?

Custom events in LWC are used for component-to-component communication. Especially between a parent and its child component, it allows the child to send messages or data up to the parent.

Can I send more than one piece of data with a custom event?

Absolutely! While our example showed sending a single message, you can send an entire object filled with data. Just make sure the receiving component knows how to handle and display that data.

How do I catch or handle a custom event in a parent component?

In the parent’s HTML, use the oneventname={handlerFunction} syntax. In our example, it was onmycustomevent={handleCustomEvent}. Then, in the parent’s JavaScript, define the handlerFunction to process the event.

Do custom events bubble up beyond the parent component?

By default, no. However, when dispatching the event from the child, you can set the bubbles property to true to make it bubble up through the component hierarchy.

Can I prevent other components from listening to my custom event?

Yes! Events in LWC have a property called composed. By default, it’s set to false, which means the event won’t reach components outside of the shadow boundary. If you want the event to pass through the boundary, set composed to true.

Is there a way to listen for custom events from unrelated components or those not in a direct parent-child relationship?

Generally, custom events are best for direct parent-child communication. If you need broader communication, you might want to look into other Salesforce mechanisms, like pub-sub or Lightning Message Service (LMS).

How do custom events in LWC compare to events in Aura components?

While both allow for component communication, they have different syntaxes and behaviors. LWC’s custom events are closer to native web standards, while Aura has its own eventing system.






Leave a Reply

Your email address will not be published. Required fields are marked *