Reputation: 115
I have two components
which displaying
each element of const elementObjects = [{id: 1, Element: "Orange", Weight: 55}, {id:2, Element: "Banana", Mass: 20}];
in an unorderd list
I want to log the value of a list item to the console if clicked
return <li onClick={(e)=> console.log(e.target.value)}>{props.value}</li>;
when clicked the eventHandler return 0
instead of Orange
how can I get the desired behavior ?
function ListItem(props) {
// --> displays the data / is reusable
return <li onClick={(e)=> console.log(e.target.value)}>{props.value}</li>;
}
function ChooseElements() {
const listItems = elementObjects.map((object) =>
<ListItem key={object.id.toString()} value={object.Element} />
);
return (
<ul>
{listItems}
</ul>
);
}
ReactDOM.render(
<ChooseElements />,
document.getElementById('root')
);
Upvotes: 1
Views: 7091
Reputation: 1908
You don't need e.target
. Your value is coming from your props. Your ListItem
should look like this to log the value once clicked:
function ListItem(props) {
return <li onClick={() => console.log(props.value)}>{props.value}</li>;
}
Upvotes: 3
Reputation: 89
You could simply pass the props.value to the onClick event handler and there won't be a need for e.target.value.
Upvotes: 0
Reputation: 183
li elements don't specifically have e.target.value So you'll have to console.log props.value
function ListItem(props) {
// --> displays the data / is reusable
return <li onClick={(e)=> console.log(props.value)}>{props.value}</li>;
}
Upvotes: 0
Reputation: 2560
Can you use value from props instead of event target?
Something like this:
function ListItem(props) {
return <li onClick={() => console.log(props.value)}>{props.value}</li>;
}
?
Upvotes: 0
Reputation: 1161
here you go. use props.value for onClick
function ListItem(props) {
return <li onClick={()=> console.log(props.value)}>{props.value}</li>;
}
Upvotes: 0