LWC – Pass event to Aura Component

auralightning-web-components

I am trying to pass an event to my parent aura component however the message within the event is always undefined.

Aura:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global">
    <lightning:card title="Aura Hello World" />
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="messageFromLwc" type="String"/>
    <c:template_Window_Navigation_VF name="testName" ontestEvent="{!c.handlefireEvent}"/>
    Message from LWC: {!v.messageFromLwc}
</aura:component>

({
    handlefireEvent : function(component, event, helper) {
        var message = event.getParam('testMessage');
        component.set("v.messageFromLwc", message);
        console.log('event.getParam:', event.getParam('testMessage'));
    }
})

LWC:

<template>
    <lightning-card title="LWC Hello World">
        <div class="slds-card__body slds-card__body_inner">
            Hello, {name}!
            <lightning-button label="Fire Event" title="FireEvent" onclick={fireEvent} class="slds-m-left_x-small"></lightning-button>
        </div>
    </lightning-card>
</template>

import { LightningElement, api } from 'lwc';

export default class Template_Window_Navigation_VF extends LightningElement {
    @api name;

    fireEvent(event){
        const selectedEvent = new CustomEvent('testEvent', { testMessage: 'Hi there' });
        this.dispatchEvent(selectedEvent);
    }
}

enter image description here

Best Answer

try sending your data using the detail property on the event's payload, something like this:

const selectedEvent = new CustomEvent('testevent', { detail: { testMessage: 'Hi there' }});

instead of this:

const selectedEvent = new CustomEvent('testEvent', { testMessage: 'Hi there' });

as you can see on Send Events to an Enclosing Aura Component article. Also, one of the suggested best practices is to avoid upper cases on the event's name, as described in the Create and Dispatch Events article.

Hope it helps.