3

I have this list:

    const chosen = (e: any) => console.log(e.target.dataset.value)

...
                <ul>
                  {numbers.map(n => (
                    <a data-value={n} onClick={chosen}>
                      <li key={n}>
                        {n}
                      </li>
                    </a>
                  ))}
                </ul>
...

It logs undefined.

Also tried this: console.log(e.target.getAttribute('data-value')) and it returns null.

How do I get the value from a tag?

Stack: TypeScript: 3.8.3, React: 16.13.1

1
  • isn't it just element.getAttribute(attributeName); ? Commented Jun 17, 2020 at 15:20

4 Answers 4

3

In frameworks like React and Vue you generally stay away from reading data from the DOM when possible. In this case, you can capture the value in a function:


    const chosen = (e: any, value: any) => console.log(value)

...
                <ul>
                  {numbers.map(n => (
                    <a key={n} onClick={(event) => { chosen(event, n); }}>
                      <li>
                        {n}
                      </li>
                    </a>
                  ))}
                </ul>
...
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the following code to do that:

export default function App() {
  function chosen(event) {
    const meta = event.target.parentNode.getAttribute("data-value");
    console.log(meta);
  }

  return (
    <ul>
      {numbers.map((n) => (
        <a data-value={n} onClick={chosen}>
          <li key={n}>{n}</li>
        </a>
      ))}
    </ul>
  );
}

Comments

0

li element should contentin the a element. Please try this example

import React from "react";

const numbers = [1, 2, 3, 4, 5];

function App() {
  function chosen(event) {
    event.preventDefault();

    console.log(event.target.dataset.value);
  }

  return (
    <ul>
      {numbers.map((number) => {
        return (
          <li key={number}>
            <a href="!#" onClick={chosen} data-value={number}>
              {number}
            </a>
          </li>
        );
      })}
    </ul>
  );
}

export default App;

And follow the Ross Allen advice

Comments

0

Access attributes from the currentTarget instead like this :

console.log(e.currentTarget.getAttribute('data-value'))

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.