Reputation: 189
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
Upvotes: 0
Views: 74
Reputation: 566
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>
);
Upvotes: 0
Reputation: 870
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>
);
Upvotes: 1