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

Categories

ReactSelect V2 and V3 seems to have several props like clearValue, resetValue and setValue. Whatever I'm trying, I'm not able to clear the selections programmatically. resetValue seems not to be accessible from the outside.

selectRef.setValue([], 'clear')
// or
selectRef.clearValue()

This does not clear the current selection.

Do I miss something here or is it not fully implemented yet?

See Question&Answers more detail:os

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

1 Answer

If you're using react-select you can try to pass null to value prop.

For example:

import React from "react";
import { render } from "react-dom";
import Select from "react-select";

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

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

    this.state = {
      select: {
        value: options[0], // "One" as initial value for react-select
        options // all available options
      }
    };
  }

  setValue = value => {
    this.setState(prevState => ({
      select: {
        ...prevState.select,
        value
      }
    }));
  };

  handleChange = value => {
    this.setValue(value);
  };

  handleClick = () => {
    this.setValue(null); // here we reset value
  };

  render() {
    const { select } = this.state;

    return (
      <div>
        <p>
          <button type="button" onClick={this.handleClick}>
            Reset value
          </button>
        </p>
        <Select
          name="form-field-name"
          value={select.value}
          onChange={this.handleChange}
          options={select.options}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Here's a working example of this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...