2
votes

I would like to change two fields values of a form at once in Redux-Form. There exists a change method, but it allows change only one field. Is there any way how to change more then one field value at once, please?

Ex.

Fields:
  - patternType
  - color

I would like to set both fields at once.

2
Hey! How's it going? Did you find a solution yourself? Would be nice to hear if my answer was useful at all, or if I misunderstood your question. - jonahe

2 Answers

0
votes

You can pass onChange callback to Field component and along with change action you can:

import React from 'react'
import { Field, reduxForm } from 'redux-form'

const TwoFieldsForm = props => {
  const { handleSubmit, change } = props
  return (
    <form onSubmit={handleSubmit}>
          <Field
            name="someField"
            component="input"
            type="text"
            onChange={(event, newValue) => change("otherField", newValue)}
          />
    </form>
  )
}

export default reduxForm({
  form: 'form' 
})(TwoFieldsForm)

see in the docs

-1
votes

Not sure if there's a better way but this way works if you want two change the value of two inputs, based on the change of just one:

const Form = ({change, dispatch}) => {
    const onFirstChange = (event) => {
      const text = event.target.value;
      // make change actions for both inputs
      const changeFirst = change('first', text);
      const changeSecond = change('second', text + text.toUpperCase());
      // dispatch them for both
      dispatch(changeFirst);
      dispatch(changeSecond);
  };
  return (<div>
    First: <Field name='first' component='input' type='text' onChange={onFirstChange} /><br />
    Second: <Field name='second' component='input' type='text' />
  </div>
    )
};

const MyForm = reduxForm({
  form: 'foo'
})(Form);

// END EXAMPLE
ReactDOM.render(
    <Provider store={store}>
    <MyForm />
  </Provider>,
  document.getElementById('root')
);

JSFiddle demo: https://jsfiddle.net/jonahe/399cpnz1/1/