Search code examples
javascriptarraysreactjsconditional-statementsdestructuring

How write my condition when using destructuring when mapping over an Array of objects


I am working with the following array of objects:

var persons: {
    label: string;
    value: string;
}[]

I iterate over the array like this:

   {persons?.map((person) => {
      return (
        <button
          key={person.value}
          data-active={value === person.value}
        >
          {person.label}
        </button>
      );
    })}

Now I use destructuring so I don't have to write person.value etc all the time, so I don't have redundant code:

   {persons?.map(({ value, label }) => {
      return (
        <button
          key={value}
          // data-active={value === person.value}
        >
          {label}
        </button>
      );
    })}

But how do I get my boolean now data-active={value === person.value} (since now {value === value} is always true)?


Solution

  • If you want to use destructuring, you need to avoid shadowing your existing value variable. You can use renaming in your destructuring pattern:

    {persons?.map(({ value: thisValue, label }) => {
       return (
         <button
           key={thisValue}
           data-active={value === thisValue}
         >
           {label}
         </button>
       );
    })}
    

    ...but I'd lean toward renaming your outer value variable instead, perhaps calling it activeValue. Then you don't need the renaming:

    const activeValue = /*...*/;
    // ...
    {persons?.map(({ value, label }) => {
       return (
         <button
           key={value}
           data-active={activeValue === value}
         >
           {label}
         </button>
       );
    })}