Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set select default value doesn't work

Using Bulma CSS for a little help I made custom component to make me handle different kind of inputs with redux-form.

I would like to setup a default value for a select input.

import React from 'react';
import { Field } from 'redux-form';

const DropDownItem = ({ spec }) => {
  const { name, defaultValue, items, iconLeft } = spec;

  return (
    <div className="field">
      <div className="control has-icons-left">
        <div className="select is-fullwidth">
          <Field name={name} value={defaultValue} component="select">
            {/* loop for countries */}
            {items.map((country, i) => (
              <option value={country} key={i}>
                {country}
              </option>
            ))}
          </Field>
        </div>
        <div className="icon is-left">
          <i className={iconLeft} />
        </div>
      </div>
    </div>
  );
};

export default DropDownItem;

I have the right value in defaultValue but the dropdown doesn't select this value by default.

like image 903
Ragnar Avatar asked Jan 28 '23 12:01

Ragnar


2 Answers

The value of a <Field /> is controlled by the value in the redux-form store. You should set the initialValues for your redux-form form in the config when you initialize it:

import React from 'react'
import { Field, reduxForm } from 'redux-form'

let MyFormComponent = props => {
    const { handleSubmit } = props;
    return (
        <form onSubmit={handleSubmit}>
            <Field name="fieldName" component="input" /> // this field's default value will be 'defaultValue', as set in initialValues
            ...
        </form>
    )
}

MyFormComponent = reduxForm({
    form: 'myForm',
    initialValues: {
        'fieldName': 'defaultValue',
        ...
    }
})(MyFormComponent)

export default MyFormComponent;

You can also pass initialValues as a prop to your form component.

source

like image 153
inostia Avatar answered Feb 16 '23 00:02

inostia


Seems like defaultValue has been disable in redux-form according to this thread on Github

Instead you can make use the initialValues API of redux-form

You can read more about initialValues on Redux Form Docs or initializefromstate

like image 42
Aaqib Avatar answered Feb 15 '23 22:02

Aaqib