Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate through list elements in react?

I am unable to figure out how to iterate through the rendered List in React Js and access the key and value properties.

Code snippet

const Cards = ({arr}) => {
  return (
    <ul className='output'>
      {arr.map(e => {
        return <li key={e.id} className="card" >
          {e.value}
          <FaTimes color='red' style={{cursor: 'pointer'}} onClick={e => console.log(e.value)}/>
        </li>
      })}
    </ul>
  )
}

Clicking the icon <FaTimes color='red' ... /> should log the value of key to the console, but instead it is returning undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The onClick handlers will receive the mouse event as a parameter. So the e you pass to that is a different e than the one you use in your iteration.

Use

onClick={() => console.log(e.value)}

and it will work.


Or just use a different name to avoid the variable shadowing

onClick={(event) => console.log(e.value)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading