Home > Back-end >  Handling keys with react props
Handling keys with react props

Time:10-07

First I had passed JSX directly to the dataarray constant. So now I try to assign a different key to each item, because console.log always returned the same key, no matter which item I clicked on. Now I have rewritten the code and created another component which is read into the constant. Unfortunately, when I click on the entry, I only get the message "undefined". So the key is not passed. Number and Time are displayed.

const ListItem = (props) => {
  return (
    <li class="date" onClick={() => handleDel(props.index)}  key={props.index}>
      <div class="number">
        <a href="tel:PHONE_NUM">{props.number}</a>
      </div>
        <div class="time">
        {props.time}
        </div>
    </li>
  )
}
for (var index in data) {
  i  ;
  dataarray.push(<ListItem key={index} number={data[index]['number']} time={data[index]['time']} />)
}
...

return (
          <ul class="list">{daten}</ul>
      )

CodePudding user response:

If you do a for loop using the in syntax you don't have to do i . Your code is messy I assume that index and i are the same variable but you renamed it. If so then commenting out i would fix it. index is automatically incremented when using the for loop with in.

Your question is focused on onClick delete returning undefined that's because your not passing the index prop to ListItem

dataarray.push(
      <ListItem
        index={index} // adding this line fixes it
        key={index}
        number={data[index]["number"]}
        time={data[index]["time"]}
      />
    ); 

take a look at this codesandbox sample https://codesandbox.io/s/boring-williams-msfgm?file=/src/App.js:583-746

  • Related