How to programmatically clear/reset React-Select?

谁都会走 提交于 2019-11-30 07:26:06

问题


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?


回答1:


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.




回答2:


I came across this problem myself and managed to fix it by passing a key to the React-Select component, with the selected value appended to it. This will then force the ReactSelect to re-render itself when the selection is updated.

I hope this helps someone.

import ReactSelect from 'react-select';

...

<ReactSelect
  key={`my_unique_select_key__${selected}`}
  value={selected || ''}
  ...
/>



回答3:


Just store the value in the state, and change the state programmatically using componentDidUpdate etc...

class Example extends Component {

constructor() {
    super()
}

state = {
     value: {label: 'Default value', key : '001'}
}

render() {
   return(
      <Select
         ...
         value={this.state.value}
         ...
      />
   )
)}

Note: 'value' should be an object.




回答4:


In case it helps anyone, this is my solution: I created a button to clear the selected value by setting state back to it's initial value.

<button onClick={() => this.clearFilters()} >Clear</button>

clearFilters(){
    this.setState({ startTime: null })
}

Full code sample below:

import React from "react"
import Select from 'react-select';

const timeSlots = [
    { value: '8:00', label: '8:00' },
    { value: '9:00', label: '9:00' },
    { value: '10:00', label: '10:00' },
] 

class Filter extends React.Component {

  constructor(){
    super();
    this.state = {
      startTime: null,
    }
  }
  
  startTime = (selectedTime) => {
    this.setState({ startTime: selectedTime });
  }

  clearFilters(){
    this.setState({
        startTime: null, 
    })
  }

  render(){
    const { startTime } = this.state;
    
    return(
      <div>
        <button onClick={() => this.clearFilters()} >Clear</button>
        <Select
            value={startTime}
            onChange={this.startTime}
            options={timeSlots}
            placeholder='Start time'
        />
      </div>
    )
  }

}

export default Filter



回答5:


This is my working implementation of a React-Select V3 cleared programmatically with Hooks.

You can play with it in the CodeSandbox DEMO. Any feedback is welcome.

const initialFormState = { mySelectKey: null };

const [myForm, setMyForm] = useState(initialFormState);

const updateForm = value => {
  setMyForm({ ...myForm, mySelectKey: value });
};

const resetForm = () => {
  setMyForm(initialFormState);
};

return (
  <div className="App">
    <form>

      <Select name = "mySelect"
           options = {options}
             value = {options.filter(({ value }) => value === myForm.mySelectKey)}
    getOptionLabel = {({ label }) => label}
    getOptionValue = {({ value }) => value}
          onChange = {({ value }) => updateForm(value)} />

      <p>MyForm: {JSON.stringify(myForm)}</p>

      <input type="button" value="Reset fields" onClick={resetForm} />

    </form>
  </div>
);



回答6:


If you check Select component in React Developers panel you will see that it is wrapped by another – State Manager. So you ref is basically ref to State manager, but not to Select itself.

Luckily, StateManager has state) and a value object which you may set to whatever you want.

For example (this is from my project, resetGroup is onClick handler that I attach to some button in DOM):

<Select onChange={this.handleGroupSelect} 
      options={this.state.groupsName.map(group => 
                  ({ label: group, value: group }) )}
      instanceId="groupselect"
      className='group-select-container'
      classNamePrefix="select"
      placeholder={this.context.t("Введите название")}
      ref={c => (this.groupSelect = c)}
/>

    resetGroup = (e) => {
        e.preventDefault()
        this.setState({
            selectedGroupName: ""
        })
        this.groupSelect.state.value.value = ""
        this.groupSelect.state.value.label = this.context.t("Введите название")
    }




回答7:


A simple option would be to pass null to the value prop.

<Select value={null} />



回答8:


If someone looking for solution using Hooks. React-Select V3.05:

const initial_state = { my_field: "" }

const my_field_options = [
    { value: 1, label: "Daily" },
    { value: 2, label: "Weekly" },
    { value: 3, label: "Monthly" },
]

export default function Example(){
    const [values, setValues] = useState(initial_state);

    function handleSelectChange(newValue, actionMeta){
        setValues({
            ...values,
            [actionMeta.name]: newValue ? newValue.value : ""
        })
    }

    return <Select
               name={"my_field"}
               inputId={"my_field"}
               onChange={handleSelectChange}
               options={my_field_options}
               placeholder={values.my_field}
               isClearable={true}
           /> 
}



回答9:


I use redux-observable.

Initial state:

firstSelectData: [],
secondSelectData:[],
secondSelectValue: null

I create an action for filling first select. on change of first select, I call an action to fill second one.

In success of fill first select I set (secondSelectData to [], secondSelectValue to null)

In success of fill second select I set (secondSelectValue to null) on change of second select, I call an action to update secondSelectValue with the new value selected



来源:https://stackoverflow.com/questions/50412843/how-to-programmatically-clear-reset-react-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!