Paras Bansal
Paras Bansal

Reputation: 71

React Button element id giving empty string

I want to pass the id of my Button in my function call when the button is clicked. But How to do that? I read the available solutions but nothing helped me.

Problem: The below code prints an empty string in the console

Expectation: paras123 should get printed

<TableCell align="center">
   <Button id="paras123" onClick={(e)=>console.log(e.target.id)}>
      Pre-Session Form
   </Button>
 </TableCell>

Upvotes: 0

Views: 670

Answers (2)

Ko Nyan
Ko Nyan

Reputation: 106

Check the target value : console.log(e.target). It will response following like that

<span class="MuiButton-label">Pre-Session Form</span>

There is no id value. If your idea is to print paras123, check this example link.

https://codesandbox.io/s/damp-paper-ftumv?file=/src/App.js:1592-1595

Upvotes: 0

Viet
Viet

Reputation: 12807

Because target is the span show text Pre-Session Form. You need use currentTarget to get button id:

onClick={(e) => console.log(e.currentTarget.id)}

Upvotes: 2

Related Questions