Salesforce Development Tutorial (LWC): How to use Data Attributes to easily pass data from your component HTML template to your JavaScript Controller

What are Data Attributes and Why Should I Use Them?

Data attributes are a truly magical thing that will, at some point, get you out of some prickly situations as a front end developer. They are essentially a way of storing data on an html element so that when a JS event gets fired your JS controller can easily get access to the data on the HTML element that fired the event.

This is especially useful in scenarios where you want to use for:each templates to generate tables, tabs or whatever else on the screen.


How to use Data Attributes (Example Code and Explanation)

Using data attributes is easy peasy lemonnnnnnnnnnn squezzyyyyyyyy… I’m sorry, it just felt right. Seriously though, it’s easy. Let’s first take a look at how we setup our HTML Template to use data attributes on a button element.

<template>
<lightning-button onclick={getDataAttributes} label="Click Me Bruh" data-donkey="donkeysAreKewl" data-turtle="NinjaTurtles"></lightning-button>
</template>

You see those weird attributes on my element? The “data-donkey” and “data-turtle” attributes? Those are data attributes and as you can see they can be named anything! However they must be in this format: data-randomnameyouchoose. Anything can come after the “data-” when setting up the data attributes on your element (do make sure each attribute has a unique name though!). Pretty cool right? The best part comes next though! Let’s check out the JavaScript Controller’s getDataAttributes method.

import {LightningElement} from 'lwc';

export default class LwcDataAttributes extends LightningElement {
	getDataAttributes(event){
		console.log('This is the data set ::: ' + 
                JSON.stringify(event.target.dataset));
		console.log('This is the data set turtle ::: ' + 
                JSON.stringify(event.target.dataset.turtle));
	}
}

You see that console log that has the “event.target.dataset” value in it? That event.target.dataset produces a Map that houses all of your data attributes in it. The output looks like this:

{"donkey":"donkeysAreKewl","turtle":"NinjaTurtles"}

As you can see it’s a key value pair, the key is whatever you named your data attribute on the HTML Element (notice the data- is excluded however) and the value is whatever value you assigned to that element on your HTML Element.

Now, you may also noticed in the console log below that one that we have the “event.target.dataset.turtle”, this line directly accesses the “data-turtle” value so it will just output “NinjaTurtles”. Pretty niftyyyyy! If you used event.target.dataset.donkey you would get the “donkeysAreKewl” value.

And to be honest that’s really all there is to it, there is one other quick thing we should review though.


What is an Event and the Difference between event.target and event.currentTarget

Boy oh boy does this really confuse people, so let me break it down right quick. Whatever element has the JS event attached to it is the one sending the event parameter to your JS method when you trigger the event (for instance when you use an onclick JS event on an HTML element and then click it to invoke the JS method). THIS IS IMPORTANT! I say this because, it is… trust me, but more importantly you can get into some tricky situations with event.target and event.currentTarget.

The key difference here is that event.target is the TRUE TARGET OF YOUR CLICK! and event.currentTarget is the ELEMENT THAT FIRED THE JS EVENT!

Even if you’ve never done it, you can sometimes wrap multiple elements within a div, and that div is actually the one that houses the onclick event. If you click a button within that div, the button is the “event.target” and the div is the “event.currentTarget”. Be wary of this! If you start to see null values or values you don’t expect in your dataset in your JS controller, this is more than likely why! It has confused many a person (including myself), so just make sure you are paying close attention to which target you are using in your controller.


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Salesforce Development Tutorial(LWC): How to Generate a Word Document from a Lightning Web Component

Why Create an LWC that can Generate Word Documents?

This is a little more self explanatory than many of the blog posts I do, but let’s go over some things. You typically wanna create this because the business has a need (for one reason or another) to generate a word doc. I’ve had businesses need them so important people could sign off on something with a hand written signature, needed guest list printed for campaigns/events and several other scenarios.

As far as why we should use an LWC to do this instead of a VF Page or Aura Component, Aura Components are considerably slower and I would just suggest not making them anymore in general and VF Pages suffer from view state limitations. While it’s easier to deal with them when working with external libraries because of lightning locker service, it’s easy to generate a document with images that blows past the 170kb view state limit and then crashes your page.


The docx.js Javascript Library

To generate word documents, we need to use the docx.js javascript library, which thankfully, is locker service compliant! Saves us a lot of time (if you didn’t know you can modify most libraries to make them compliant). You can get the docxjs code we’re gonna be using for this tutorial here .

This library basically allows you to generate word documents using javascript. It makes your life doing this a thousand times easier, so make sure to thank the devs that built it!


Writing the Code

The code we’re gonna write to get this done is just for a simple example. We’re gonna generate a list of contacts associated with an account in a word document. Before we get started, all this code is up on my GitHub here, so if you wanna just ignore this whole section and check out the GitHub repo, feel free, otherwise, please carry on, lol. So first things first, open up VSCode and create a new lightning web component! If you aren’t familiar with how to setup VSCode, I have a video covering it here!

Once you’ve got your new LWC created in VSCode, we need to upload the docxjs code to static resources so that we can use it in our LWC. You can grab the docxjs code here. Then navigate to static resources in setup and upload the docxjs code there. Make sure to make the static resource public!

After that’s done, switch back over to VSCode and let’s import the docxjs file into the LWC by using the code below:

import { LightningElement} from 'lwc';
import {loadScript} from "lightning/platformResourceLoader";
import docxImport from "@salesforce/resourceUrl/docx";

export default class Contact_list_generator extends LightningElement {

    connectedCallback(){
        Promise.all([loadScript(this, docxImport)]).then(() =>{
            //call some code here
        });
    }
}

You may be looking at the above like, “wtf is that bro?” so let me explain. The connectedCallback method is called when your LWC is loaded into the browser, so it’s kinda like the init method in Aura components. Promise.all is just saying, “Hey, I promise to wait until all the scripts are loaded, then I’m gonna execute the code inside this code block”. The loadScript is a module that Salesforce provides to you that allows you to load in resources to your LWC from static resources. Last, but certainly not least, the, “import docxImport from “@salesforce/resourceUrl/docx”;” is the actual reference to your docx static resource file. The docx at the end of the of that line should be whatever you actually named your static resource.

Next let’s add the html below to our LWC

<template>
    <div class="slds-p-bottom_x-large">
        <lightning-button class="hidden slds-float_left slds-p-right_medium" onclick={startDocumentGeneration} label="Build Document"></lightning-button>
        <a href={downloadURL} download="ContactList.docx" class="slds-hide slds-button slds-button_brand slds-float_left" >Download Document</a>         
    </div>
</template>

In the HTML above we’re basically just creating two buttons, one to generate a word document and one to download that word document. You’ll notice there are two references in the HTML to js variables/methods that don’t exist yet (startDocumentGeneration and downloadURL) so let’s get back to the LWC js controller and figure this thing out.

The next thing we need to add is a way to render the generate document button after the component loads the docxjs script. We can do that with the following code

    connectedCallback(){
        Promise.all([loadScript(this, docxImport)]).then(() =>{
            this.renderButtons();
        });
    }

    renderButtons(){
        this.template.querySelector(".hidden").classList.remove("hidden");
    }

In our connected callback method we’re gonna call a method called renderButtons that changes the visibility of our buttons after our scripts are loaded. The “this.template.querySelector(“.hidden”).classList.remove(“hidden”);” is removing the class that was hiding the component and allowing it to be viewed and clickable. We do need to actually add the css though. So let’s add the css below to the component

.hidden{
    display: none;
}

Basically that css just allows you to hide an element… pretty simple. Not much there.

The next thing we need to do is create the startDocumentGeneration method and actually grab our contact data and build the document. So let’s look at the rest of the controller code we need to build out below.

import { LightningElement, api } from 'lwc';
import {loadScript} from "lightning/platformResourceLoader";
import docxImport from "@salesforce/resourceUrl/docx";
import contactGrab from "@salesforce/apex/ContactGrabber.getAllRelatedContacts";

export default class Contact_list_generator extends LightningElement {

    @api recordId;
    downloadURL;
    _no_border = {top: {style: "none", size: 0, color: "FFFFFF"},
	bottom: {style: "none", size: 0, color: "FFFFFF"},
	left: {style: "none", size: 0, color: "FFFFFF"},
	right: {style: "none", size: 0, color: "FFFFFF"}};

    connectedCallback(){
        Promise.all([loadScript(this, docxImport)]).then(() =>{
            this.renderButtons();
        });
    }

    renderButtons(){
        //this.template.querySelector(".hidden").classList.add("not_hidden");
        this.template.querySelector(".hidden").classList.remove("hidden");
    }

    startDocumentGeneration(){
        contactGrab({'acctId': this.recordId}).then(contacts=>{
            this.buildDocument(contacts);
        });
    }

    buildDocument(contactsPassed){
        let document = new docx.Document();
        let tableCells = [];
        tableCells.push(this.generateHeaderRow());

        contactsPassed.forEach(contact => {
            tableCells.push(this.generateRow(contact));
        });

        this.generateTable(document, tableCells);
        this.generateDownloadLink(document);
    }

    generateHeaderRow(){
        let tableHeaderRow = new docx.TableRow({
            children:[
                new docx.TableCell({
                    children: [new docx.Paragraph("First Name")],
                    borders: this._no_border
                }),
                new docx.TableCell({
                    children: [new docx.Paragraph("Last Name")],
                    borders: this._no_border
                }) 
            ]
        });

        return tableHeaderRow;
    }

    generateRow(contactPassed){
        let tableRow = new docx.TableRow({
            children: [
                new docx.TableCell({
                    children: [new docx.Paragraph({children: [this.generateTextRun(contactPassed["FirstName"].toString())]})],
                    borders: this._no_border
                }),
                new docx.TableCell({
                    children: [new docx.Paragraph({children: [this.generateTextRun(contactPassed["LastName"].toString())]})],
                    borders: this._no_border
                })
            ]
        });

        return tableRow;
    }

    generateTextRun(cellString){
        let textRun = new docx.TextRun({text: cellString, bold: true, size: 48, font: "Calibri"});
        return textRun;
    }

    generateTable(documentPassed, tableCellsPassed){
        let docTable = new docx.Table({
            rows: tableCellsPassed
        });

        documentPassed.addSection({
            children: [docTable]
        });
    }

    generateDownloadLink(documentPassed){
        docx.Packer.toBase64String(documentPassed).then(textBlob =>{
            this.downloadURL = 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,' + textBlob;
            this.template.querySelector(".slds-hide").classList.remove("slds-hide");
        });
    }
}

So, there’s a bit to cover here, lol, so let’s start with the call in to the apex controller to get our contacts. This line of code here:

contactGrab({'acctId': this.recordId}).then(contacts=>{
            this.buildDocument(contacts);
        });

This calls to the apex controller and retrieves a list of contacts based on the account id of the record we’re currently on. If you didn’t know, the @api recordId variable declaration at the top of the class just dynamically pulls in the id of the record your component is being viewed on! Super convenient! We are also able to call our apex method using the contactGrab({‘acctId’: this.recordId}) statement because we imported our apex class at the top of the LWC here “import contactGrab from “@salesforce/apex/ContactGrabber.getAllRelatedContacts”;”. That being said we haven’t looked at the apex code yet, so let’s check it out… there’s not much there but it’s still important.

public with sharing class ContactGrabber {
    @AuraEnabled
    public static List<Contact> getAllRelatedContacts(Id acctId){
        return [SELECT Id, FirstName, LastName FROM Contact WHERE AccountId = :acctId];
    }
}

The @AuraEnabled declaration allows us to import this method in our class to the LWC. It’s import to do that, so don’t forget!

Now that we have our contacts we actually need to generate the document. So let’s get to it bruh! The buildDocument method starts this process so let’s check it our first.

buildDocument(contactsPassed){
        let document = new docx.Document();
        let tableRows = [];
        tableRows.push(this.generateHeaderRow());

        contactsPassed.forEach(contact => {
            tableRows.push(this.generateRow(contact));
        });

        this.generateTable(document, tableRows);
        this.generateDownloadLink(document);
    }

In the code above we’re declaring a new docx Document object with the “new docx.Dcoument()” declaration. After this we create an array of table cells (because in this example we are building a table of contacts in a word document). We then proceed to push a table row into the table rows array by calling the generateHeaderRow method in our js controller. Let’s check out that class next.

generateHeaderRow(){
        let tableHeaderRow = new docx.TableRow({
            children:[
                new docx.TableCell({
                    children: [new docx.Paragraph("First Name")],
                    borders: this._no_border
                }),
                new docx.TableCell({
                    children: [new docx.Paragraph("Last Name")],
                    borders: this._no_border
                }) 
            ]
        });

        return tableHeaderRow;
    }

The generateHeaderRow method use the docx.TableRow object, the docx.TableCell object and the docx.Paragraph object to generate a table row with two cells. One cell for the contacts first name and another cell for a contacts last name. It then returns this table row.

Let’s get back to the buildDocument method now. The next thing that happens is we iterate through the list of contacts that we pulled from our apex controller and generate a table row for each contact by calling the generateRow method and push that into our tableRows array. So let’s look at the generateRow method next.

generateRow(contactPassed){
        let tableRow = new docx.TableRow({
            children: [
                new docx.TableCell({
                    children: [new docx.Paragraph({children: [this.generateTextRun(contactPassed["FirstName"].toString())]})],
                    borders: this._no_border
                }),
                new docx.TableCell({
                    children: [new docx.Paragraph({children: [this.generateTextRun(contactPassed["LastName"].toString())]})],
                    borders: this._no_border
                })
            ]
        });

        return tableRow;
    }

This code does something similar to the generateHeaderRow method, the only difference between the two is that I call the generateTextRun method instead of just outright declaring a new docx Paragraph object. The docx.TextRun object allows us to specify traits in our text. Things like font size, font type, whether the text is bold and a ton more. Let’s check out the generateTextRun method to see what it’s doing.

generateTextRun(cellString){
        let textRun = new docx.TextRun({text: cellString, bold: true, size: 48, font: "Calibri"});
        return textRun;
    }

In the method above we are generating what docxjs calls a text run and then returning it. It’s pretty simple as you can see. I’m just declaring the traits I want for my text. Nothing more, nothing less.

Back to the buildDocument method then! The next thing we do is call the generateTable method and pass is our docx.Document object along with our array of tableRows. Let’s check out that method next!

generateTable(documentPassed, tableCellsPassed){
        let docTable = new docx.Table({
            rows: tableCellsPassed
        });

        documentPassed.addSection({
            children: [docTable]
        });
    }

In this method we are creating a new docx.Table and assigning the array of rows we passed to this method to the rows parameter of the docx.Table. We then proceed to add a new section to our docx.Document and put the table in that section. This actually adds the table to the document we are creating.

Now, one last time, let’s check out the buildDocument method again. The last thing we do in it is call the generateDownloadLink method. So let’s take a look at that method now.

generateDownloadLink(documentPassed){
        docx.Packer.toBase64String(documentPassed).then(textBlob =>{
            this.downloadURL = 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,' + textBlob;
            this.template.querySelector(".slds-hide").classList.remove("slds-hide");
        });
    }

What this method does, is take the document we built and create a url that will allow us to download the word doc. It also turns on the download button in our LWC. We generate a base64 encoded string using the docx.Packer object and assign it to the downloadURL.

And believe it or not, that’s it! Yea!!! You’ve just figured out how to build your own LWC that can produce word documents. You can build off this base to do whatever you think you might wanna do. You could, with the help of other js libraries build a whole document templating app. I’ve done it in the past, it’s challenging, but doable! Good luck building whatever it is you’re building with this!


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Salesforce Development Tutorial (LWC): How to create Custom Lightning Web Component Utility Modules

Why create Utility Modules for Lightning Web Components?

If you’re asking this question, I have feeling you don’t often utilize utility modules (or utility classes) anywhere… so let me be the first to welcome you to this absolutely magical world of utilities. They will make your life easier, code updates simpler and your code base a lot less terrifying.

Utility modules are useful in LWC’s because they allow you to take code you commonly use (or may commonly use) between components and allow tons of different components to use that same code without re-writing it a bunch.

Here’s a simple example. Say you pull URL parameters in several different lightning web components and in all of those components you have the exact same method that parses the url and returns those parameters. Instead of adding that method to every single component and having to update that method any time your process for parsing URL parameters change, you could just make a javascript utility module to deal with it, import it into your components and just call that single javascript utility module everywhere you needed to parse URL parameters. In the end this greatly reduces your codebase and the difficulty updating your code in the future.

Maybe the above is still confusing, no worries, let’s check out an example that will hopefully clear any confusion up.


How to create a Utility Module

So to give you a little background on what we’re about to do, I would suggest a little light reading on ES6 Javascript Modules. This will give you a bit better understanding on how all this code I’m about to show you works. If you’re not as obsessive of a reader as me, don’t worry though, I’ll explain everything just a bit throughout the rest of this post.

The first thing we need to do is create an LWC and delete the html file that comes with it as well as all the pre-built code in the javascript file. You might be like wutttttttt??????? But no worries, with utility modules you won’t need them. I know it feels weird right now, but just trust ya boi for one sec.

Next let’s take a look at a very simple LWC module with some exports in it. The name of the below LWC is “util_module”. Knowing the below components name will be important in the near future (GitHub where this code is also available).

//DISCLAIMER: There are many different ways available in ES6 JS to export variables, functions and classes
//you can find out more about exports here: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

//How to export a variable and make it available when importing your module
//in other components
export const OPEN_STATUS = 'Open';

//How to export a method and make it available when importing your module
//in other components
export function showError(error) {
    return 'This is an error ' + error;
}

//How to export a class and make it available when importing your module
//in other components
export class util_class {

    newStatus = 'New';

    showConsoleLog(){
        console.log('This is the console log ::: ');
    }

}

So what is all that junk up there? It’s not all that complicated after you get familiar with it. Basically what you are seeing are a handful of ways to make things accessible in a javascript module. The key thing here is that “export” keyword. Placing the export keyword in front of a variable, function or a class will allow you to import them into other components. Which brings us to the next part of this lesson, “How tf do we use this utility module”. Let’s check that out.


How to Import/Use your LWC Utility Module

Alright my guys (and gals), let’s check out the code to import that adorable little utility class we made up there into one of our normal LWC’s .

import { LightningElement } from 'lwc';

//Importing in our javascript utility module. The import variable names (OPEN_STATUS, //showError, util_class)
//are the names of the exported variable, method and class in our util_module component
import { OPEN_STATUS, showError, util_class} from 'c/util_module';

export default class Demo_component extends LightningElement 
{
    openStatus;
    returnedError;
    newStatus;

    //The connectedCallback method runs on component load
    connectedCallback()
    {
        //assigning our imported OPEN_STATUS value to our local openStatus variable
        this.openStatus = OPEN_STATUS;

        //assigning our imported showError methods return value to our local returnedError 
        //variable 
        this.returnedError = showError('Tacos had an error');

        //assigning our imported class's newStatus variable to our local newStatus variable
        this.newStatus = new util_class().newStatus;

        //Calling our imported class's showConsoleLog method
        new util_class().showConsoleLog();
    }
}

You’re thinking one of two things right now. It’s either, “Whoa my guy, it’s really that easy?” or, “Idk wtf that mess means”. For the group in latter, let me help you get into the former group with a little bit of an explanation.

Near the top of our LWC you’ll notice this line:

import { OPEN_STATUS, showError, util_class} from 'c/util_module';

This statement is importing the this various things we marked with the “export” keyword in the util_module LWC we created above. You will notice that the OPEN_STATUS, showError and util_class all are the exact names of the things with the “export” statement next to them in the util_module LWC.

These OPEN_STATUS, showError and util_class imports now become accessible in your class via those keywords. So for instance when we do this assignment:

this.openStatus = OPEN_STATUS;

We are literally assigning the OPEN_STATUS variable value from our util_module LWC to our local openStatus variable. Pretty cool right? Hopefully this makes things a little clearer… maybe… If I’m lucky anyway.

And that’s really it everyone! If you have any questions feel free to ask. I typically respond pretty quick.


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Salesforce Development (LWC): How to Communicate between Aura Components and Lightning Web Components Using Custom Events and the Api Decorator

Why Would You Want to Communicate Between Component Types?

There are a bunch of reasons it’s beneficial to communicate between component types but the most common ones that I have found are the following:

1) You’re building a new component and realize you need functionality that only Aura Components support, but it’s a very small piece of the component. Instead of building the entire thing in an outdated and much less performant Aura Component, you build most of it in an LWC and just communicate to a small Aura component to do the function only it can do.

2) You’re staffed in an Aura heavy org and when you start building new things for the existing Aura components you should build them in LWC. You can easily do this, but you need to know how the communication channels work between component types.

Once you see how easy it is to communicate between components it’ll be much easier to switch to LWC’s to do development for everything moving forward.


How to Communicate from an LWC to an Aura Component

This is super simple but it’s confusing if you’ve never done it before. We’re basically just gonna create a custom event in our LWC and handle that event in the Aura Component. Let’s check out the code and then I’ll explain it a bit:

<!--This is the LWC HTML-->
<template>
    <lightning-input class="dataToSend" placeholder="Enter text to transfer">
    </lightning-input>
    <lightning-button variant="brand" label="Pass data to Aura Component" 
    onclick={communicateToAura} ></lightning-button>
</template>
//This is the LWC JS Controller
import {LightningElement} from 'lwc';

export default class LwcCommunication extends LightningElement
{
    //This method creates a custom event that dispatches itself.
    //The Aura component then handles this event
    communicateToAura()
    {
         console.log('Communicating to Aura ::: ');

         //We are grabbing the value from the lightning input field that has the dataToSend 
         //class
         let dataToSend = this.template.querySelector(".dataToSend").value;

        //We are creating a custom event named senddata and passing a value in the detail 
        //portion of the custom event
        const sendDataEvent = new CustomEvent('senddata', {
            detail: {dataToSend}
        });

        //Actually dispatching the event that we created above.
        this.dispatchEvent(sendDataEvent);
    }
}
<!--This is the Aura Component HTML-->
<aura:component description="Aura_Communication">
	<aura:attribute name="dataReceived" type="String"/>

	<!--The onsenddata is what handles the custom event we made in our LWC-->
	<c:lwc_Communication onsenddata="{!c.receiveLWCData}" aura:id="lwcComp" />
        <p>This is the data receieved from our LWC: {!v.dataReceived}</p>
</aura:component>
({
       //This is the Aura JS Controller
	
        //This method receives data from our LWC and sets the dataReceived
	//Aura attribute with the events dataToSend parameter (this is the name of the 
        //variable we send in the LWC)
	receiveLWCData : function(component, event, helper)
	{
	    component.set("v.dataReceived", event.getParam("dataToSend"));
	}
});

Alright so now that you’ve checked out the code let’s go over this just a lil bit. In the communicateToAura method above you can see that we create a CustomEvent object and we give it the name ‘senddata’, we also pass some data in the custom event by using the detail property of our Javascript custom event object.

Then in the Aura component’s html we can see that we import our lightning web component using this line:

<c:lwc_Communication onsenddata="{!c.receiveLWCData}" aura:id="lwcComp" />

You can see that when we import our lightning web component that we have an onsenddata event that calls a method in the Aura Components javascript controller called receiveLWCData. When you dispatch your senddata event in your lightning web component the Aura component handles it with the onsenddata event attached to the lightning web component.

Finally you can see that we get the data from the event that was passed to us in the receieveLWCData in the Aura Components JS controller. The most important part of the method is the event.getParam(“dataToSend”). You are grabbing the variable that you passed into the detail property of your CustomEvent object in your LWC. Let me put them side by side so you see exactly what I mean:

//LWC Custom Event code
const sendDataEvent = new CustomEvent('senddata', {
            detail: {dataToSend}
});

//Aura code
component.set("v.dataReceived", event.getParam("dataToSend"));

And believe it or not it’s really that simple. You have successfully passed data from your LWC to your Aura component. Now let’s figure out how to do this in reverse.


How to Communicate from an Aura Component to an LWC

Alright so how do we do the exact opposite of what we did above?? It’s pretty simple but we need to leverage the wonderful @api decorator for lightning web components to make this work as opposed to Aura event communication. Alright so let’s check out the code below and then I’ll go over it a bit more in detail:

<!--This is the LWC Template/HTML-->
<template>
	<p>This is the data received from the Aura Component: {dataReceived}</p>
</template>
//This is the LWC JS Controller
import {LightningElement, api, track} from 'lwc';

export default class LwcCommunication extends LightningElement
{
	//Tracked variables ensure that they are refreshed on the page when their values are
	//updated in the code
	@track dataReceived;

	//The api decorator makes this a public method that any component that houses this 
        //component can access/call
	@api receiveData(data)
	{
	    this.dataReceived = data;
	}
}
<!--Aura Component HTML-->
<aura:component description="Aura_Communication">

	<!--The onsenddata is what handles the custom event we made in our LWC-->
	<c:lwc_Communication aura:id="lwcComp" />

	<lightning:input aura:id="dataToPass" />

	<lightning:button label="Pass data to LWC" onclick="{!c.passDataToLWC}"/>
</aura:component>
({
        //This is the Aura Component JS Controller

	//This method sends out data to our LWC from the Aura component.
	passDataToLWC : function(component, event, helper)
	{
		let stringToSend = component.find("dataToPass").get("v.value");

		//We are calling the receieveData method in our Lightning Web Component here
		component.find("lwcComp").receiveData(stringToSend);
	}
});

Alright, so as you can see nothing super complicated just some weird stuff you may not be super comfortable with yet. There are two very important pieces to making the passage of data between components possible.

The first is the @api method in the LWC. The receiveData method has the @api decorator in front of it. This makes the method public available to its parent component regardless of what component type it is.

The second is the component.find(“lwcComp”).receiveData(stringToSend) line in the passDataToLWC method in the Aura Components Javascript controller. This is finding the lwc that we imported into our Aura Component by its aura:id and then calling the receiveData method in the LWC (the method with the @api decorator) and passing it data.

This is surprisingly simple thankfully, no weird hacky tricks necessary just a few lines of code and we’re all good to go! If any of this is super confusing please check out the video above. I go over every aspect of the code in great detail.


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps