0

According to the documentation on the React SLDS Button:

Although not listed in the prop table, all aria-*, data-* and form* props will be added to the button element if passed in.

So my button:

<Button
    className="slds-button_neutral"
    data-value="test"
    label="My Button"
    onClick={handleClick}
>
</Button>

And my handler:

const handleParentSelect = (event: any) => {
    console.log(event.target.getAttribute('data-value'));
};

event.target.attributes does NOT contain data-value at all (I did actually try typing the click event as well with no luck). The documentation says this should work, but it doesn't. Am I missing a piece here? Or is documentation just wrong?

2 Answers 2

1

data-* attributes are generally available on the dataset property.

Please try event.target.dataset.value or event.currentTarget.dataset.value

9
  • 2
    Also, documentation.
    – sfdcfox
    Aug 12, 2021 at 15:09
  • Hmmm still getting undefined with that. The button ends up looking like this: <button class="slds-button slds-button_neutral" type="button">My Button</button> Which I think is the problem. That data attribute is not getting passed back to the button like the documentation says it should be. Aug 12, 2021 at 15:15
  • Could be because value is a keyword. Try renaming the attribute to data-val, and then use event.target.dataset.val Aug 12, 2021 at 15:20
  • data-val didn't work either. I am not sure if typescript is messing with the event somehow? Aug 12, 2021 at 15:26
  • 1
    So aria-* attributes show up in the attribute list and I can access them. So aria-valuenow works I guess for my use case... But really not sure why data- attributes are not working when documentation says they are. Aug 12, 2021 at 15:49
1

It might be because you probably have children inside the button. In this case JS handles click event on one of the children.

https://javascript.info/bubbling-and-capturing

Generally it should work with event.currentTarget.dataset.value. But anyway there are at least 2 more solutions:

1) JS

const handleClick = ({ nativeEvent }) => {
  let target = nativeEvent.target as HTMLElement;
  while (target.className !== 'slds-button_neutral') {
    target = target.parentNode;
  }
  const value = target.dataset.value;
  ...
}

2) CSS

.slds-button_neutral * {
  pointer-events: none;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .