Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65941267/programmatically-change-the-value-of-react-select-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...