hidace hidace - 1 month ago 27
React JSX Question

How to export mapStateToProps and Redux Form?

I'm using Redux Form (ver. 6) for a log in page. What I would like to do is when the user fills out the form and clicks submit, grab the text from my state so that I can eventually dispatch an action with that email and password. However, I'm having trouble with exporting this component while using both connect from react-redux and Redux Form.

Using react-redux, connect wants to be exported like so when mapping state to props:

export default connect(mapStateToProps)(LogInForm)

However, Redux Form wants it's export set up like this:

export default reduxForm({
form: 'LogInForm',
validate,
})(LogInForm);


Is there a way to combine these two? I'd tried something like:

const reduxFormConfig = reduxForm({
form: 'LogInForm',
validate,
});

export default connect(mapStateToProps)(ReduxFormConfig)(LogInForm)


but it did not work.

Or Perhaps that's a better approach to handling this? Here is the full code from within my component:

import React from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import InputField from '../InputField';
import { validateLogInSignUp as validate } from '../../utils/validateForms.js';

const LogInForm = (props) => {
const {
handleSubmit,
pristine,
submitting,
} = props;

return (
<div>
<form onSubmit={handleSubmit}>
<Field
name="email"
type="email"
component={InputField}
label="email"
/>
<Field
name="password"
type="password"
component={InputField}
label="password"
/>
<div>
<button type="submit" disabled={submitting}>Submit</button>
</div>
</form>
</div>
);
};

const mapStateToProps = state => {
return {
loginInput: state.form,
};
};

// export default connect(mapStateToProps)(LogInForm)

// export default reduxForm({
// form: 'LogInForm',
// validate,
// })(LogInForm);


Any and all help is much appreciated. Thanks!

Answer

Using redux-form you shouldn't need to access the state directly in your LoginForm. Instead, you should access the values in your parent component when the form is submitted:

// LoginForm.js
const LogInForm = (props) => {
  ...
};

export default reduxForm({
  form: 'LogInForm',
  validate,
})(LogInForm);


// Parent.js
import LoginForm from './LoginForm';

const handleSubmit = (values) => {
  alert(JSON.stringify(values));  // { email: 'foo@bar.com', password: '1forest1' }
};

const Parent = (props) => {
  return (
    <LoginForm onSubmit={ handleSubmit } />
  );
};

See https://github.com/erikras/redux-form/blob/master/examples/simple/src/index.js#L42 for a more complete example of a simple form.