Thinker
Thinker

Reputation: 5366

React-Select multivalue does not populate selected items like in example

I am trying to use react-select (https://github.com/JedWatson/react-select) in my application, I have a select box whose options are loaded dynamically (i.e. I make a call to backend to fetch data). Right now I can see all the options populated in my dropdown, however when I click on any item onChange() event works but the element is not de-populated from the dropdown and shown at the top like a tag as shown in the official example. My select box:

<Select
    multi={true}
    name="form-field-name"
    options={this.props.metadata ? this.props.metadata["latest"].languages : []}
    labelKey="display_name"
    valueKey="id"
    onChange={this.addLanguage}
    clearable={false}
    value="id"
/>

This shows me on UI:

enter image description here

Here I have already selected two elements from the list but they are not shown on the top like following example:

enter image description here

I have imported js and css in my component as following:

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

UPDATE

When added multiple items: enter image description here

Upvotes: 0

Views: 3400

Answers (1)

Cagri Yardimci
Cagri Yardimci

Reputation: 3529

It is probably because you set the field value="id" In official documentation value field is defined as initial field value

So basically, in your snippet a static value is initially assigned and not getting any updates as you select more results.

In author's example code, multi select component is used like the following:

<Select 
  multi 
  simpleValue 
  disabled={this.state.disabled} 
  value={this.state.value} 
  placeholder="Select your favourite(s)" 
  options={this.state.options} 
  onChange={this.handleSelectChange} />

So whenever there is a change, onChange event uses handleSelectChange method.

handleSelectChange (value) { console.log('You\'ve selected:', value); this.setState({ value }); },

This method then updates this.state.value which is used to display the selected values of component.

I don't know what your this.addLanguage method currently does, but if we take author's example as a baseline, what you need to to is instead of value="id" you should update it as value={this.state.value} and with your this.addLanguage method, you should update the value of this.state.value

Upvotes: 1

Related Questions