reactjsreact-reduxreact-redux-form

Initialize redux form controls with state to props


Packages used

"react-redux": "^5.0.6",
"redux-form": "^8.2.5",
"react": "^16.4.2",

Here is the component

class EditProfileForm extends Component {
 return(
       <div>
       <Field name="firstName" component="input" >
       </div>
      )
}

EditProfileForm = reduxForm({    
    form: 'EditProfileForm'
})(EditProfileForm);

const mapStateToProps = state => ({
  initialValues: state.profile.firstName
})

export default connect(mapStateToProps)(EditProfileForm);

Issue facing:

Invariant Violation: You must pass a component to the function returned by connect. Instead received {"displayName":"ReduxForm","defaultProps":{"touchOnBlur":true,"touchOnChange":false,"persistentSubmitErrors":false,"destroyOnUnmount":true,"enableReinitialize":true,"keepDirtyOnReinitialize":false,"updateUnregisteredFields":false,"pure":true,"forceUnregisterOnUnmount":false,"submitAsSideEffect":false,"form":"EditProfileForm"}}

Solution

  • There are two mistakes in your component

    1) You are using a class component, which implies it needs to extend Component (which you have done) with a render method (you have missed this) in it, which will return the JSX markups.

    class EditProfileForm extends Component {
      render() {
        return (
          <div>
            <Field name="firstName" component="input"/>
          </div>
        );
      }
    }
    

    2) initialValues prop needs to be an object not a value

    const mapStateToProps = state => ({
      initialValues: state.profile
    });
    

    In case you were trying to create a Functional Component, here is the solution

    let EditProfileForm = () => {
      return (
        <div>
          <Field name="firstName" component="input"/>
        </div>
      );
    };
    
    EditProfileForm = reduxForm({
      form: 'EditProfileForm'
    })(EditProfileForm);
    
    const mapStateToProps = state => ({
      initialValues: state.profile
    });
    
    export default connect(mapStateToProps)(EditProfileForm);