2
votes

I'm using a redux-form and have a custom component that uses react-select.

I have created dropdown that has prefilled options and also allows custom input into that dropdown box. I am using the "creatable" componant from react-select.

I want to be able to have one of the options as the default value on first load, this option would be highlighted in the dropdown list as selected too. I have achieved this but the only problem is, if I choose a new value or create a new value it stays as the default value - although the json does change to the correct value.

Here is my codesandbox example - https://codesandbox.io/s/jvzko04ok3

In my example you will see that Jim is selected by default, but as soon as you change the select option to something else the json values change but the view does not. Have a feeling its a onBlur or onChange issue.

There has been version changes to the react-select docs over the years, a default value can be specified using value or defaultValue.

  <CreatableSelect
    {...props}
    options={props.options}
    onChange={value => input.onChange(value)}
    onBlur={() => input.onBlur(input.value)}
    value={props.options[1]}
  />
2

2 Answers

2
votes

This is because you've tied the value prop directly to props.options[1], which doesn't change. Better to tie it to a state variable that you default to the option, and have your onChange update the state variable.

0
votes

Inspired by the accepted answer of Steves. I converted my stateless component into a class component and gave it a default state and handled the onChange.

Here is a codesandbox for other that may need a solution - https://codesandbox.io/s/kyr9mwpr5

From this:

const LastNameSelectInput = ({ input, ...props }) => (
  <CreatableSelect
    {...props}
    options={props.options}
    // menuIsOpen={true}
    onChange={value => input.onChange(value)}
    onBlur={() => input.onBlur(input.value)}
    value={props.options[1]}
  />
);

to this:

  class LastNameSelectInput extends React.Component {
  constructor(props) {
    super(props);
  }

  state = { value: this.props.options[1] };

  render() {
    const { input, options } = this.props;
    return (
      <CreatableSelect
        options={options}
        // menuIsOpen={true}
        onChange={value => {
          let newValue = input.onChange(value);
          this.setState({ value: newValue });
        }}
        onBlur={() => input.onBlur(input.value)}
        value={this.state.value}
      />
    );
  }
}