Search code examples
javascriptreactjsreact-reduxredux-form

Pass initial value to redux-form


I want to pass initial values (coming from the props of a react-redux component) to my redux-form. But, I get not value when I inspect the data passed to the renderField . I followed the posts here in SO and on redux-form git forum, and I'm using initialValues in mapStateToProps but still it doesn't work.

This is my react-redux component which holds the redux-form:

class ShowGroup extends Component {

  render() {
    if (this.state.loading) {
      return <div>Loading group ....</div>;
    }
    if (this.state.error) {
      return <div>{this.state.error}</div>;
    }
    let group = this.props.groups[this.groupId];
    return (
      <div className="show-group">
        <form>
          <Field
            name="name"
            fieldType="input"
            type="text"
            component={renderField}
            label="Name"
            validate={validateName}
          />
        </form>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    groups: state.groups,
    initialValues: {
      name: 'hello'
    }
  };
}

const mapDispatchToProps = (dispatch) => {
    return {
             //.....
    };
};

export default reduxForm({
  form:'ShowGroup'
})(
  connect(mapStateToProps, mapDispatchToProps)(ShowGroup)
);

This is my renderField code:

export const renderField = function({ input, fieldType, label, type, meta: { touched, error }}) {
  let FieldType = fieldType;
  return (
    <div>
      <label>{label}</label>
      <div>
        <FieldType {...input} type={type} />
        {touched && error && <span>{error}</span>}
      </div>
    </div>
  );
}

Solution

  • You are exporting the wrapped component with incorrect order

    export default reduxForm({
      form:'ShowGroup'
    })(
      connect(mapStateToProps, mapDispatchToProps)(ShowGroup)
    );
    

    should be

    export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({
      form:'ShowGroup'
    })(ShowGroup);
    

    The reason being that the redux form HOC needs the initialValues prop for itself, if you reverse the order, reduxForm doesn't get the props rather they are passed directly to the component, which doesn't know what to do with it.