Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Material-UI Button attribute in onClick?

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

like image 891
Preeti Avatar asked Oct 18 '25 16:10

Preeti


1 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

like image 126
NearHuscarl Avatar answered Oct 20 '25 05:10

NearHuscarl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!