My work projects rely heavily on the use of Redux Form (paired with React). A problem I struggled with was trying to figure out how to pre-populate my form with initial values. It wasn’t so straightforward as the form was nested in a customized dialogue component and I could not use the initialValues prop like so: <Form initialValues={} />
If you are in a similar position or just want to figure out various ways to utilize initial values in your Redux form, keep reading on!
Let’s use a simple form as an example:
1) Pass initialValues prop in form instance component
We pass a prop called initialValues
into the form instance component and the value is an object with the keys being the name of the field and the values being the initial value which we want to add.
<SimpleForm
onSubmit={this.handleSubmit}
initialValues={{name: "Sherlynn"}}
/>
Another way would be to store the values in a variable. This is useful especially when there are many form fields.
var initialName = {name: "Sherlynn" }<SimpleForm
onSubmit={this.handleSubmit}
initialValues={initialName}
/>
2) Add initialValues prop in mapStateToProps
You can use the initalValues prop in mapStateToProps.
- Convert your form to a React Component
- Import
connect
fromredux-react
- Add
initialValues
prop inmapStateToProps
and you can retrieveinitialValues
from the redux store - To pass the
initialValues
props into the redux form, we use theconnect
function (Line 34 onwards) - Add
enableReinitialize : true
When set to true, the form will reinitialize every time the initialValues prop changes
That is it! Refresh the app and you should see the initial values appear on your Redux form field.