Dustyik
Dustyik

Reputation: 69

React: How can i access a attribute within a <td> tag

in my code, i am trying to pass some data from my onClick() function

<TableCell value={i} align="center" onClick={e => this.deleteUser(e)}><DeleteIcon /></TableCell>

My table cell is created in a for loop, and it is assigned the value i when it is first created. When the delete user icon is clicked, i want the value i to be passed along as well. in my onClick function, the even is passed along

deleteUser(e) {
        console.log(e.currentTarget). 
    }

this is my delete user function. When i test the function with console.log(). This is printed

<td class="MuiTableCell-root MuiTableCell-alignCenter" value="0"> ... </td>

How can i get value from within the td tag? I cant access it with event.currentTarget.value

Upvotes: 0

Views: 939

Answers (2)

Giwan
Giwan

Reputation: 1590

You can use the getAttribute property of the currentTarget. https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

function handleclick(e) {
var val = e.getAttribute("value");
console.log("test " + val); 
}
<table>
<tr><td value="55" onclick="handleclick(this)">test</td></tr>
</table>


Since it's React you might want to provide the i value in the onClick directly.

<TableCell align="center" onClick={e => this.deleteUser(i)}><DeleteIcon /></TableCell>

Upvotes: 2

Amit Chauhan
Amit Chauhan

Reputation: 6899

Pass i to your deleteUser function

<TableCell value={i} align="center" onClick={e => this.deleteUser(e, i)}><DeleteIcon /></TableCell>

you will get value as a second argument

deleteUser(e, value) {
  console.log(e.currentTarget, value); 
}

Upvotes: 3

Related Questions