reactjsredux-formreact-select

React select set initial value with Redux Form


I'm trying to set an initial value for my Select tag using Redux Form field.

Redux Field:

<Field
                    name="statusDto.pkid"
                    component={renderSelectField}
                    type="text"
                    isHidden="true"
                    placeholder="Select Status"
                    options={userRegistrationStatus && userRegistrationStatus.map((values) => { return ({ value: values.pkid, label: i18next.languages[0] === 'en' ? values.enName : values.trName }); })}
                  />

Redux Form:

UserRegistrationForm = reduxForm({
  validate,
  form: 'User_Registration_Form', // a unique identifier for this form
  enableReinitialize: true,
})(UserRegistrationForm));

React Select:

handleChange = (selectedOption) => {
    const { onChange } = this.props;
    this.setState({ selectedOptionState: selectedOption });
    onChange(selectedOption.value);
  };

 <Select
        name={name}
        value={selectedOptionState}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />

Using redux-form initialize, I try to assign the first value to react-select but it doesn't seem to be worth it. Can you help me?


Solution

  • I solved the problem.

    React Select:

    <Select
            name={name}
            value={(value === '') ? null : options.find(obj => obj.value === value)}
            onChange={this.handleChange}
            styles={customStyles}
            options={options}
            clearable={false}
            className="react-select"
            placeholder={placeholder}
            isDisabled={isDisabled}
            classNamePrefix="react-select"
            theme={(theme) => ({
              ...theme,
              borderRadius: 0,
              colors: {
                ...theme.colors,
                primary: '#70bbfd',
              },
            })}
          />