AlexGilleran / jsx-control-statements

Neater If and For for React JSX
https://www.npmjs.com/package/babel-plugin-jsx-control-statements
MIT License
1.62k stars 64 forks source link

Destructing For #56

Open navgarcha opened 7 years ago

navgarcha commented 7 years ago

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}>

AlexGilleran commented 7 years ago

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

texttechne commented 7 years ago

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?

navgarcha commented 7 years ago

Agree on those points @texttechne.

navgarcha commented 7 years ago

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>
AlexGilleran commented 7 years ago

@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?

texttechne commented 7 years ago

@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 }) => {
    //...
  })
}