Will Will - 3 months ago 69
React JSX Question

How to get Field value and pass it to FieldArray value with Push event? Redux-Form V6-RC3

I have a FieldArray component supposed to show telephones.
The user can add a telephone object containing a number Field, a type Field and a button to add the phone into the phone list(FieldArray).

The Phone List component contains a button with the function fields.remove(index) which I pass the phone index to.

My phone object is: {number: number, type: type}

Currently using: React 0.15.3, Redux-Form 6.0.0-rc3, Material-UI 0.15.3

Phone fields declaration:

<Field name="phoneNumber" component={renderMaskedTextField} label={"Telefone"} type="text" mask="(99) 9999-99999"/>

<Field name="phoneType" component={renderSelectField} label="Tipo">
{PHONE_TYPES.map((option, index) => {
return <MenuItem value={option.value} primaryText={option.label} key={index}/>;
})}
</Field>


Code I use to add the phone component into the list:

<IconButton onClick={() => handleAddClick({number: field.input.phone.number, type: field.input.phone.type})} style={styles.addButton}>
<Add color="#fd084a"/>
</IconButton>


I need a way to get both Field values and pass it to my handleAddClick()

Add function:

const handleAddClick = (phone) => {
fields.push(phone);
};


Also open to new ways to solve this :D

Answer

You can use the arrayPush() action creator. Then all you'll need to figure out is how to get dispatch or to pre-bind the action creator in mapDispatchToProps.

import { arrayPush } from 'redux-form'

@connect(
  mapStateToProps,
  { arrayPush }
)
class MyForm extends Component {

  ...

  handleAddClick(phone) {
    this.props.arrayPush('myForm', 'phones', phone)
  }

  ...
}

Does that help?