Search code examples
redux-form

How to manually trigger onChange event without <Field> element?


I have component that renders like this:

<MyComponent 
  prop1Value={1} 
  prop1OnChange={this.handleProp1Change}
  prop2Value={2} 
  prop2OnChange={this.handleProp2Change}
/>

So it contains two fields/values internally. How I can sync it with redux-form? <Field> component provides only one value/onChange pair...

Tried it like this:

// values comes from getFormValues(...)
<MyComponent 
  prop1Value={values.prop1} 
  prop1OnChange={this.context._reduxForm.change.bind(this.context._reduxForm, 'prop1')}
  prop2Value={values.prop2} 
  prop2OnChange={this.context._reduxForm.change.bind(this.context._reduxForm, 'prop1')}
/>

Solution

  • You'll have to use connect to bind those actions.

    import { change } from 'redux-form';
    import { connect } from 'react-redux';
    
    const ParentComponent = (props) => {
        return <div>
            <MyComponent propOneOnChange={props.change('formName', 'fieldName', 'fieldValue')} />
        </div>
    }
    
    export default connect(mapStateToProps, { change })(ParentComponent);