How to get Material-UI Button attribute in onClick?

Viewed 531

How to get the attribute of Material-UI Button?. I've tried the getAttribute() but it gives me null. I know this is possible using normal <button> tags but I want to try using Material-UI button.

My button-

<Button 
    variant="outlined" 
    id={button1} 
    button-key="buttonAttribute"
    onClick={this.isClicked}>
    MyButton
</Button>

click function -

isClicked = (e) => {
   const attButton = e.target.getAttribute('button-key')
   console.log(attButton)
}

My console returns null. How can it return buttonAttribute

2 Answers

Try using currentTarget instead

e.currentTarget.getAttribute("button-key")

You can also use data attributes by prefixing your attribute name with data-*. It's a good practice to use this instead because it creates a 'namespace' for your custom attribute so they won't clash with the standard HTML attributes.

<Button
  onClick={(e) => {
    console.log(e.currentTarget.dataset.buttonKey);
  }}
  data-button-key="buttonAttribute"
>

Live Demo

Edit 64305609/how-to-get-material-ui-button-attribute-in-onclick

It is showing null because if you log the e.target then you will see the span element which is present inside button component and you are passing id to its root element which is a div.

Related