1

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')
);





1
  • Try props.value (the value of the value prop) instead of e.target.value (the value of the value attribute of the li HTML element, which is unlikely to be anything interesting, since you haven't set it to anything interesting. Commented May 2, 2021 at 18:10

5 Answers 5

3

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>;
}
Sign up to request clarification or add additional context in comments.

Comments

0

here you go. use props.value for onClick


function ListItem(props) {
  return <li onClick={()=> console.log(props.value)}>{props.value}</li>;
}

Comments

0

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

?

Comments

0

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

Comments

0

You could simply pass the props.value to the onClick event handler and there won't be a need for e.target.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.