1

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

enter image description here

in cnsole when click on links

enter image description here

1 Answer 1

1

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

7 Comments

What is printed ? Are you sure that every entry has an id property ?
printed only id of the last elements, every entry has an id property because it s data from db,
This is really weird, can you console.log your entries array in the render function, right before the return, and tell me what it shows ?
add pic to question
Alright, thank you for the update, I think this should solve it
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.