React + Redux Form — Two ways to add initial values

Sherlynn Tan
Jan 1 · 2 min read
Because Redux aka Re(ducks). Lol. Bad joke, sorry not sorry.

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:

Simple Redux Form with a single “Name” field

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.

  1. Convert your form to a React Component
  2. Import connect from redux-react
  3. Add initialValuesprop in mapStateToProps and you can retrieve initialValues from the redux store
  4. To pass the initialValues props into the redux form, we use the connect function (Line 34 onwards)
  5. 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.

Sherlynn Tan

Written by

Software Developer at Thoughtworks | Marathon Runner | Ex-Pharmacist Writing on Coding, Technology and Running

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade