LWC Button pass a value to the JS Method

buttonjavascriptlightning-web-components

I have a two buttons defined in my LWC

 <lightning-button
      variant="brand-outline"
      label="Age"
      title="Age"
      onclick={handleClick}
      class="slds-var-m-left_x-small"
      data-id="age"
    ></lightning-button>

    <lightning-button
      variant="brand-outline"
      label="Name"
      title="Name"
      customvalue="customValue"
      onclick={handleClick}
      class="slds-var-m-left_x-small"
      data-id="name"
    ></lightning-button>

In my JS I have the following method

handleClick(event){
console.log(event.target.name)  //doesn't work
console.log(event) //doesn't work
console.log(this) //doesn't work
console.log(tis.name) // doesn't work
}

The end goal I'm seeking is to know which of the two buttons have been pushed so I can have my code behave accordingly.

How do I do detect which button was clicked?

Best Answer

LWC components dispatch a CustomEvent

To get data out of this component, the convention is to look for

event.detail.value if it's a publicly exposed value on that component.

If you are in the same shadow tree, you can use event.target.value

In your instance, you need to use detail.value to get the value, because you can't see inside that component.

If you wanted to get data-id="age" from the event, you should use:

event.target.dataset.id

more details here