0

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

2
  • use e.target.value instead Commented Apr 23, 2022 at 8:25
  • Thanks. Tried but still the same unfotunately. Commented Apr 23, 2022 at 8:28

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.