This is my code,
import "./styles.css";
import React from "react";
export default function App() {
const categories = [
{ name: "aaa", slug: "aaa" },
{ name: "baa", slug: "baa" }
];
const handleClick = (value) => {
console.log(value);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div>
<ul>
{categories.map((category) => (
<li className="cat_item" key={category.slug}>
<a
value="value"
onClick={(e) => handleClick(e.currentTarget.value)}
className="dropdown-item"
>
{category.name}
<span className="text-gray-25 font-size-12 font-weight-normal"></span>
</a>
</li>
))}
</ul>
</div>
</div>
);
}
But whn I click it appear as undefined instead of value in log. Here is a fiddle of issue
CodePudding user response:
This is because the target is the HTML anchor element itself and thus doesn't have a value property associated with it. In your case, I'm assuming you want to get the text within the your anchort element, try this instead.
onClick={(e) => handleClick(e.target.textContent)}
And we can use this for custom attributes,
onClick={(e) => handleClick(e.target.attributes.getNamedItem("value").value)}
Source is here
CodePudding user response:
you have try to pass the value. But here no any input field that's why undefined here. You have try to pass innerText content.
onClick={(e) => handleClick(e.currentTarget.innerText)}