Maximus S Maximus S - 1 month ago 20
React JSX Question

Redux Form Variables

import React, { Component, PropTypes } from 'react'
import { reduxForm } from 'redux-form'
export const fields = [ 'firstName', 'lastName', 'email', 'sex', 'favoriteColor', 'employed', 'notes' ]

class SimpleForm extends Component {
render() {
const {
fields: { firstName, lastName, email, sex, favoriteColor, employed, notes },
handleSubmit,
resetForm,
submitting
} = this.props
return (<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<input type="text" placeholder="First Name" {...firstName}/>
</div>
</div>
<div>
<label>Last Name</label>
<div>
<input type="text" placeholder="Last Name" {...lastName}/>
</div>
</div>
<div>


This is a
Simple Form
example from
redux-form
package. I am puzzled where the variable
firstName
come from. Is there something I'm missing from the ES6 syntax?

Answer

The ES6 concept you might be missing is called "destructuring object assignment":

This assignment:

const {
  fields: { firstName, lastName, email, sex, favoriteColor, employed, notes },
  handleSubmit,
  resetForm,
  submitting
  } = this.props

means that this.props has the shape

{ fields: { firstName: "...", 
            lastName: "...", 
            email: "...", 
            sex: "...", 
            favoriteColor: "...", 
            employed: "...", 
            notes: "..."
          },
  handleSubmit: "...",
  resetForm: "...",
  submitting: "..."
}

where "..." stands for any datatype (including objects and arrays), not just Strings. Also, the object may contain more information than that.

Destructuring assignment allows to deeply reach into the object structure and assign names to elements of that object. In our case, each of the "..." values I sketched above is directly assigned to a variable. These variables can subsequently be used on their own. That's where firstName comes from.

The code then applies another new ES6 thing called the "object spread operator": Passing {...firstName} allows to split up the firstName object and to pass each of its properties to the React component individually. Say, firstName looks like this:

{ a: "...", b: "...", c: "..." }

then

<MyComponent {...firstName} />

is equivalent to

<MyComponent a={firstName.a} b={firstName.b} c={firstName.c} />
Comments