Redux form defaultValue

Андрей Гузюк picture Андрей Гузюк · Apr 26, 2017 · Viewed 29.5k times · Source

How to set defaultValue to input component?

<Field name={`${prize}.rank`} defaultValue={index} component={Input} type='text'/>

I tried like above but my fields are empty. I'm trying to create fieldArray (dynamic forms):

{fields.map((prize, index) =>
    <div key={index} className="fieldArray-container relative border-bottom" style={{paddingTop: 35}}>
        <small className="fieldArray-title marginBottom20">Prize {index + 1}
            <button
                type="button"
                title="Remove prize"
                className="btn btn-link absolute-link right"
                onClick={() => fields.remove(index)}>Delete</button>
        </small>
        <div className="row">
            <div className="col-xs-12 col-sm-6">
                <Field name={`${prize}.rank`}  defaultValue={index} component={Input} type='text'/>
                <Field name={`${prize}.prizeId`} defaultValue={index} component={Input} type='text'/>
                <Field
                    name={`${prize}.name`}
                    type="text"
                    component={Input}
                    label='Prize Name'/>
            </div>
            <div className="col-xs-12 col-sm-6">
                <Field
                    name={`${prize}.url`}
                    type="text"
                    component={Input}
                    label="Prize URL"/>
            </div>
            <div className="col-xs-12">
                <Field
                    name={`${prize}.description`}
                    type="text"
                    component={Input}
                    label="Prize Description" />
            </div>
        </div>
    </div>
)}

Answer

philipp picture philipp · Apr 26, 2017

On redux forms you can call initialize() with an object of values like so:

class MyForm extends Component {
  componentWillMount () {
    this.props.initialize({ name: 'your name' });
  }

  //if your data can be updated
  componentWillReceiveProps (nextProps) {
    if (/* nextProps changed in a way to reset default values */) {
      this.props.destroy();
      this.props.initialize({…});
    }
  }

  render () {
    return (
      <form>
       <Field name="name" component="…" />
      </form>
    );
  }
}

export default reduxForm({})(MyForm);

This way you can update the default values over and over again, but if you just need to do it at the first time you can:

export default reduxForm({values: {…}})(MyForm);