I am unable to select the listItem properly
I am a beginner to React and i am having trouble in iterating through List Item in Material UI . I am iterating through a json array and adding list item to a list. On clicking any list item , the list always selects the last item
function handleListItemClick(index) {
setSelectedIndex(index);
props.user.updateState(index);
props.user.setCourseName(props.mycourses[index].courseName);
}
function RenderListItem(props) {
var indents = [];
let ind = 0;
for (var key in props.coursevals) {
indents.push(
// <span>
<ListItem
button
selected={selectedIndex === key}
onClick={() => handleListItemClick(key)}
// onClick={event => handleListItemClick(event, 0)}
className={classes.ListItem}
key={key}
>
{/* {console.log(key)} */}
<ListItemIcon>
<img
className={classes.courseimg}
src="../../../public/images/book.png"
/>
</ListItemIcon>
<ListItemText primary={props.coursevals[key].courseId} />
<img
className={classes.rightarrow}
src="../../../public/images/rightarrow.png"
/>
</ListItem>
);
}
return indents;
}
OnClick Event always send the last index to the function. I want to send the index where i just clicked