Duck Jones
Duck Jones

Reputation: 390

Programmatically change the value of react-select component

I'm using the react-select component in a React app pretty heavily. I've created a wrapper component which allows me to specify a use-case where I want the selected value to reset on selection.

My component wrapper is defined as:

import React, { useRef } from 'react';
import Select from 'react-select'
export const SelectComponent = (props) => {
    const selectRef = useRef(null);

    const valueSelected = (item) => {
        if (!item || item.value === props.selectedValue) {
            return;
        }

        if (props.resetOnSelect) {
            selectRef.current.select.clearValue();
        }
        props.onValueSelected(item);
    }

    return <div className="modal-form-row">
        <Select ref={selectRef} options={props.options} onChange={valueSelected} id={props.id} isClearable={true} isSearchable={true} placeholder={props.label} value={props.selectedValue} />
    </div>;
}

And this is how the component gets referenced:

const options = [
    { label: 'Item1', value: '1' },
    { label: 'Item2', value: '2' },
    { label: 'Item2', value: '2' },
];
<SelectComponent id="select-list" label="Pick an Item" options={options} onValueSelected={this.handleNewItem} value="" resetOnSelect={true} />

It appears to be working, as my valueSelected handler is called a second time with a null argument, but the select component itself doesn't re-render, it leaves the user's selection showing. Any ideas on what I should try next?

Upvotes: 3

Views: 7001

Answers (1)

kca
kca

Reputation: 6121

Just pass null to the value (or empty string):

<Select ... value={ null } />

It behaves just like any other contolled component:

  • The onChange handler is called with the new value
  • the value is set, in this case to null

Note that you had set value to props.selectedValue, which is undefined, and if value is undefined (or not given at all), the uncontrolled-component-behavior is used.

Upvotes: 3

Related Questions