Reputation: 101
How can I get the id of a list's elements in a map function ?
export default class PhotoSlider extends Component {
handleSort(value) {
console.log(value)
}
render()
{
return photo.map((entry, index) => <Link to='#' onClick={() => this.handleSort(entry.id)}>... </Link>)
}
}
The console only prints the id of the last element
in cnsole when click on links
Upvotes: 1
Views: 8204
Reputation: 7492
Using onClick={() => this.handleSort(entry.id)}
will not call your function when clicking, it will assign what your function returns to the click event.
The following code preconfigures your function to send the id of your entry as well as the click event arguments using arrow functions :
export default class PhotoSlider extends Component {
handleSort = value => event => {
console.log(value)
}
render()
{
return photo.map(entry => <Link to='#' onClick={this.handleSort(entry.id)}>... </Link>)
}
}
Also, don't forget to add a key to your components when using map :
photo.map(entry => <Link to='#' key={entry.id} onClick={this.handleSort(entry.id)}>... </Link>)
Also, try indenting your code correctly when asking a question, as I did in my edit to your question (for example)
EDIT : I think I figured it out :
In React, your render function is supposed to send a single HTML node, which could be the reason why only the last Link is used.
If you are using the latest version of React, you can wrap your map in a fragment :
export default class PhotoSlider extends Component {
handleSort = value => event => {
console.log(value)
}
render()
{
return (
<>
{photo.map(entry => <Link to='#' onClick={this.handleSort(entry.id)}>... </Link>)}
</>
)
}
}
Otherwise, just use a div (or React.Fragment) :
export default class PhotoSlider extends Component {
handleSort = value => event => {
console.log(value)
}
render()
{
return (
<div>
{photo.map(entry => <Link to='#' onClick={this.handleSort(entry.id)}>... </Link>)}
</div>
)
}
}
Upvotes: 1