-1
Fala galera
Maybe it’s a simple problem but I’m trying to figure out why it doesn’t work, I researched here in the stack, I found similar questions but they didn’t solve the problem.
I have a dynamically mounted table according to the API
I need to get the TR (parent) ID of the TD element I clicked.
Problem:
- It only works after the second click
- After the third click, the item is printed repeatedly on the console
It seems that it is printed the amount of times it has already been clicked.
Tbody
<Tbody>
{address.map((index) => {
let tipoPessoa = ''
if (index.tipoPessoa === 1) {
tipoPessoa = 'Física'
}
else {
tipoPessoa = 'Jurídica'
}
return <Tr id={index.id} key={index.id} className='tr'>
<Td>{index.nome}</Td>
<Td>{index.endereco.cidade}</Td>
<Td>{tipoPessoa}</Td>
<Td onClick={detailsAddress}><Icon src={Search} /></Td>
</Tr>
})}
</Tbody>
Function to capture ID
const detailsAddress = () => {
const trs = document.querySelectorAll('.tr')
trs.forEach((tr)=>{
tr.addEventListener('click', ()=>{
console.log(tr)
})
})
}
Console

Every time the
tdis clicked, you are creating and accumulating newaddEventListenerto thetr.– Sam
Because the use of
querySelectorAllandaddEventListener? If you are in the world React should give preference touseRefandonClick.– Isac