Reputation: 316
My code is like this:
<a eventkey={0} onClick={ (event) => console.log(event.target)} href="#">
{i}
</a>
In console.log
I want to see the eventkey
value like 0.
But I'm getting the whole tag.
How should I get only the eventkey
value?
Upvotes: 2
Views: 172
Reputation: 56744
It's widely considered bad practice to make use of inline event listeners (onClick
), which is why I rewrote your code to make use of adddEventListener
. Please also note that eventkey
is an illegal attribute name on a
tags. Use data-eventkey
instead, which allows you to read it using element.dataset.eventkey
:
const eventkeyLinks = Array.from(document.querySelectorAll('[data-eventkey]'));
eventkeyLinks.forEach((link) =>
link.addEventListener('click', (event) => {
console.log(link.dataset.eventkey);
})
);
<a data-eventkey="{0}" href="#"> {i} </a>
<a data-eventkey="{1}" href="#"> {j} </a>
<a data-eventkey="{2}" href="#"> {k} </a>
<a data-eventkey="{3}" href="#"> {l} </a>
<a data-eventkey="{4}" href="#"> {m} </a>
You could also use a delegate listener which would work for dynamically added elements as well:
document.addEventListener('click', (event) => {
if (event.target.matches('[data-eventkey]')) {
console.log(event.target.dataset.eventkey);
}
})
<a data-eventkey="{0}" href="#"> {i} </a>
<a data-eventkey="{1}" href="#"> {j} </a>
<a data-eventkey="{2}" href="#"> {k} </a>
<a data-eventkey="{3}" href="#"> {l} </a>
<a data-eventkey="{4}" href="#"> {m} </a>
<a href="#"> no eventkey here </a>
Upvotes: 1
Reputation: 15688
You would need this to access your custom props.
event.target.attributes.getNamedItem("eventkey").value
Upvotes: 3
Reputation: 1085
Try
<a eventkey={0} onClick={ (event) => console.log(event.target.value)} href="#"> {i} </a>
Upvotes: -1