Search code examples
redux-form

Unclear syntax in redux-form


Having trouble understanding the syntax in redux-form...

In redux-docs

const renderField = (field) => (
    <div className="input-row">
      <input {...field.input} type="text"/>
      {field.meta.touched && field.meta.error && 
       <span className="error">{field.meta.error}</span>}
    </div>   )

How is the spread operator used inside the input and why does the following returnes an error:

<input {...field.input, id} type="text"/>

The second syntax I dont understand is:

class MyCustomInput extends Component {
  render() {
    const { input: { value, onChange } } = this.props  <---??
    return (
      <div>
        <span>The current value is {value}.</span>
        <button type="button" onClick={() => onChange(value + 1)}>Inc</button>
        <button type="button" onClick={() => onChange(value - 1)}>Dec</button>
      </div>
    )
  }
}

What is:

input: { value, onChange }

?


Solution

  • Queston 1:

    The error from using {...field.input, id} should be something like the following:

    Syntax error: ...: Unexpected token, expected }
    

    If you already have props as an object, and you want to pass it in JSX, you can use ... as a “spread” operator to pass the whole props object (Spread Attributes)

    So it appears the JSX attribute spread is not exactly the same as a es2015 spread. I believe it is limited to just the examples in the react docs.

    Question 2:

    The Field component passes these props to your wrapped component MyCustomInput

    input.onChange(eventOrValue) : Function A function to call when the form field is changed. It expects to either receive the React SyntheticEvent or the new value of the field.

    input.value: any The value of this form field. It will be a boolean for checkboxes, and a string for all other input types. If there is no value in the Redux state for this field, it will default to ''. This is to ensure that the input is controlled. If you require that the value be of another type (e.g. Date or Number), you must provide initialValues to your form with the desired type of this field.

    In other words when MyCustomInput fires onChange the Field component will dispatch an action to update the form store.

    The value prop is used to maintain the state MyCustomInput.