xtabbas
xtabbas

Reputation: 647

Multi select from react-select with redux-form not working as intended

So iam using multi select from react-select with redux-form with the onBlur hack(?) which is working fine behind the curtain because when i submit it I have the selected data in values

BUT after visiting any multi select field (even if i dont select anything) I end up with no values at all (nothing is displayed but this
image ))

const options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

<Select
            value="one"
            options={options}
            multi={true}
            {...input}
            onBlur={() => {
              input.onBlur({...input.value})
            }
          }
        />

So i end up with values in the redux state but I cant see any values in the field. Anyone know why is this happening?

Upvotes: 3

Views: 4571

Answers (2)

andrewkslv
andrewkslv

Reputation: 1302

Here's example how to make it works. react-select (1.0.0-rc.2), redux-form (5.3.4)

SelectInput.js

import React from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';

export default (props) => (
  <Select
    {...props}
    value={props.input.value}
    onChange={(value) => props.input.onChange(value)}
    onBlur={() => props.input.onBlur(props.input.value)}
    options={props.options}
  />
);

MyAwesomeComponent.js

import React, {PureComponent} from 'react';
import SelectInput from './SelectInput.js';

class MyAwesomeComponent extends PureComponent {
  render() {
    const options = [
      {'label': 'Germany', 'value': 'DE'},
      {'label': 'Russian Federation', 'value': 'RU'},
      {'label': 'United States', 'value': 'US'}
    ];
  return (
    <Field
      name='countries'
      options={options}
      component={SelectInput}
      multi
    />
  )
};

Upvotes: 11

Erik R.
Erik R.

Reputation: 7272

I have not used more modern versions of react-select, but a year ago, there were some issues with having to split() the string value by the delimiter to get the values as an array, and then join() them again to give to the component.

Stuff like this:

if (multi) {
  selectValue = value ? value.join(delimiter) : ''
} else {
  selectValue = value || null
}

I recommend examining exactly what the value is in Redux, using Redux DevTools, and what value prop is getting passed to react-select. I'm sure you'll find the problem in there.

Upvotes: 1

Related Questions