Skip to content

Initial Form Values with redux-form

Posted on:November 26, 2015

Caveat emptor: I’m currently using 3.0.6 of redux-form. As with most things on the bleeding edge, this post will probably be irrelevant in a few months (or weeks).

There’re a few reasons one may need to have form values initialized upon render - edit forms, or default select values.

In vanilla HTML, one would simply do:

<select>
  <option value="apple">Apple</option>
  <option value="orange" selected>Orange</option>
</select>

It’s a little different in JSX. In JSX, Facebook recommends the following way.

To set initial form values in redux-form that are actually initialized in the Redux state, one needs to pass in an object with a initialValues main key and field key-value pairs as props to the redux-form Form component:

import { React, Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
 
import { reduxForm } from "redux-form";
import { registerPerson } from "actions/coolStuff";
 
@connect(null, dispatch => ({
  registerPerson: bindActionCreators(registerPerson, dispatch),
}))
export default class ExampleComponent extends Component {
  render() {
    const myInitialValues = {
      initialValues: {
        name: "John Doe",
        age: 42,
        fruitPreference: "apples",
      },
    };
    return (
      <div>
        <h1>Check out my cool form!</h1>
        <CoolForm
          {...myInitialValues}
          onSubmit={fields => {
            this.props.registerPerson(fields);
          }}
        />
      </div>
    );
  }
}
 
@reduxForm({
  form: "exampleForm",
  fields: ["name", "age", "fruitPreference"],
})
class CoolForm extends Component {
  render() {
    const {
      fields: { name, age, fruitPreference },
      handleSubmit,
    } = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <label>Name</label>
        <input type="text" {...name} />
        <label>Age</label>
        <input type="text" {...age} />
        <label>Do you prefer apples or oranges?</label>
        <select {...fruitPreference}>
          <option value="apples">Apples</option>
          <option value="oranges">Oranges</option>
        </select>
        <button type="submit" onClick={handleSubmit}>
          Submit
        </button>
      </form>
    );
  }
}

If all goes well, you’ll see the initial values being loaded into Redux state upon initialization, which can be submitted (to handleSubmit) right away: