0

In a section of my code, I have the following problem:

I need to access the value of a li element:

const elements = element.map((element) =>
     <li>{element}</li>
     );
<ul>
<!--I need access to this value-->
{elements}
 </ul>

example:

<li>mark</li>

value: mark

2
  • don't you still have access to element and can just lock up your value? Can you please clarify what you want and why element[0] for example is not accessible? Commented Oct 12, 2020 at 19:42
  • @ian the user clicks on the list item and depending on that click, the following actions are deterimined Commented Oct 12, 2020 at 19:51

2 Answers 2

1

You should be able to access the name of the element through a click event handler like so:

  const names = [
    'Mark',
    'John',
  ];

  const handleClick = (event) => {
    const { name } = event.target;

    // you now have access to name
  };

...other code

  return (
    <ul>
      {names.map((name) => <li name={name} onClick={handleClick}>{name}</li>)}
    </ul>
  );

OR

  const names = [
    'Mark',
    'John',
  ];

  const handleClick = (name) => {
    // you now have access to name
  };

...other code

  return (
    <ul>
      {names.map((name) => <li onClick={() => handleClick(name)}>{name}</li>)}
    </ul>
  );

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

Comments

0

You could do something like this:

const handleClick = e => {
    let value = e.target.innerHTML; // Returns HTML + String
    // OR
    value = e.target.innerText; // Returns Just String Value
}

const elements = element.map((element) =>
     <li onClick={handleClick}>{element}</li>
);

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.