jsx-control-statements icon indicating copy to clipboard operation
jsx-control-statements copied to clipboard

Destructing For

Open navgarcha opened this issue 8 years ago • 6 comments

Are there plans to support destructing the each prop in the For control statement? For example something like this:

<For each="{ firstName, lastName }" index="i" of={this.people}>

navgarcha avatar Jan 30 '17 15:01 navgarcha

No plans, but I wouldn't be opposed to it.

AlexGilleran avatar Jan 31 '17 04:01 AlexGilleran

Nice suggestion, but it makes a strange construct even more weird.

First of all we are using a string to define a variable. That is neither elegant nor unproblematic; at least TypeScript / Flow won't accept this. On the other hand we don't know of any other way to realize this functionality. But should we really extend this syntax as you requested? Destructuring as a string doesn't seem to be a good idea. @AlexGilleran Would the linting rule you provided for the for statement even work for destructuring?

texttechne avatar Jan 31 '17 17:01 texttechne

Agree on those points @texttechne.

navgarcha avatar Jan 31 '17 18:01 navgarcha

Perhaps something like:

<For each={({ firstName, lastName }) => ({ name: `${firstName} ${lastName}` })} index="i" of={this.props.people} /> (although this can be a bit verbose)

Inside we utilise {name} inside? Or let, which i prefer, For take a function as a child and do:

<For index="index" of={items}>
    {({ firstName, lastName }) => { 
        // ...
    }}
</For>

navgarcha avatar Jan 31 '17 18:01 navgarcha

@AlexGilleran Would the linting rule you provided for the for statement even work for destructuring?

Nope :(

By the time you've done this:

<For index="index" of={items}>
    {({ firstName, lastName }) => { 
        // ...
    }}
</For>

Wouldn't you be better off just using the equivalent map call?

AlexGilleran avatar Feb 01 '17 00:02 AlexGilleran

@navgarcha you're right to use a function there to 1) create variables and 2) use those variables in the correct scope. But as soon as you use functions it defeats the purpose of the For statement. As @AlexGilleran points out, it is easier to use map directly in this case:

{
  items.map(({ firstName, lastName }) => {
    //...
  })
}

texttechne avatar Feb 02 '17 19:02 texttechne