Reputation: 185
I want to create one function that can be used for 2 onClick
s to sort objects by title
and by genre.name
in this array:
const movies = [
{
title: "Terminator",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
},
{
title: "Rat Race",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Comedy" },
},
{
title: "Get Out",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
},
]
So far, for each onClick
I had to create one function: onClick={titleSorted}
and onClick={genreSorted}
. Yet I think this is not a good practice because if I have 10 keys in one object, it'll be too many similar codes in one file.
However, if I create one function with a parameter for all onClick
s:
moviesSorted(item) => {}
then I can't use onClick={moviesSorted(title)}
or onClick={moviesSorted(genre.name)}
because it automatically runs the functions before clicking as I understand.
So please help me find a way for this. I really appreciate it!
Upvotes: 0
Views: 639
Reputation: 14901
Function passed to onClick
must be a event handler, implemented as
function(event) {
// ...
}
So you in your example, you might want
onClick={() => moviesSorted(title)}
// or
onClick={() => moviesSorted(genre.name)}
Upvotes: 2