Reputation:
UPDATED QUESTION.
I am trying to introduce a filter to my map so users can define which options they want to see with multiple selection boxes.
The problem I am facing is actually the page after they have filtered the options.
Example: I have 5 names all with different colours and with different active statuses stored in a array like so:
const info = [
{ name: "A1"
colour: "Blue"
active: "Yes"
},
{ name: "B2"
colour: "Red"
active: "Yes"
},
{ name: "C3"
colour: "Green"
active: "No"
},
{ name: "D4"
colour: "Yellow"
active: "No"
},
{ name: "E5"
colour: "Orange"
active: "Yes"
},
I filter the "non active" using
{info.filter(info => info.active.includes("Yes")).map((index, value) => {
return (
<div>{info[value].name}</div>
//THIS DOES NOT DISPLAY THE CORRECT NAME FOR A START.
<Navlink to={{ pathname: "/confirmChoices", state: {choice: value}}>CLICK</Navlink>
//THIS IS NOW PASSING THE WRONG VALUE TO THE NEXT PAGE.
)};
The page displays the correct amount of items so:
A1
CLICK
B2
CLICK
C3 // THIS SHOULD BE E5
CLICK
Now the second problem is when I want to click on C3 that should be E5. The next page loads and it displays the info for C3 and not E5.
Like so
Name: C3
COLOUR: RED
ACTIVE: NO
Upvotes: 0
Views: 147
Reputation: 20431
You aren't making use of the variable in the callback inside .map()
. That will point you to the correct value.
.filter()
and .map()
do not alter the original array and instead return a new array.
Since you are passing in the index value from the original array as a prop, you cannot use index inside your .map()
. This index(in this case 2) is not the index of E5. You will have to get the index from the original array using something like findIndex
.
{info.filter(info => info.active.includes("Yes")).map((value, index) => {
let originalIndex = info.findIndex((item)=>item.name == value.name);
return (
<div>{value.name}</div>
<Navlink to={{ pathname: "/confirmChoices", state: {choice: originalIndex }}>CLICK</Navlink>
)};
Also will suggest using better variable names. The first param in .map()
callback is the value, and second is the index.
Upvotes: 1