简体   繁体   中英

How to reset select dropdown values in react

I have one html dropdown select control and I have added first option value as Select . There are several other options to select from dropdown. Now I want to reset the dropdown values and set it back to Select .

How I can do it in React?

Here is my code

<select className="form-control" ref="Auditee" name="Auditee" onChange={this.handleChange.bind(this)}>
                <option>Select</option>
                {this.renderAuditee()}
              </select>
<button type="button" className="btn btn-primary" onClick={this.handleClear}>Clear</button>



renderAuditee(){
  let Auditeefiltered = this.state.review1data.map(element=> element.EEECPM).filter((value, index, self) => self.indexOf(value) === index)

  return Auditeefiltered.map(element=>
   <option>{element.toString().replace(/\[.*?\]/,'')}</option>
  )
}


handleClear(e){
 e.preventDefault();

    this.setState({
        filterData:[],
        filter: false
 });

I don't know how I should Reset the select dropdown. Any help would be helpful

Your select should be controlled .

You need to have a state variable for selected value.

state ={
   selected:''
}

And the controlled select should be,

<select className="form-control" value={this.state.selected} name="Auditee" onChange={this.handleChange.bind(this)}>
    <option>Select</option>
    {this.renderAuditee()}
</select>
handleChange = (e) => {
   this.setState({selected:e.target.value})
}

And finally to clear select,

handleClear = (e) => {
   this.setState({selected:""})
}

Demo

Functional component version of the above answer would be

import logo from "./logo.svg";
import "./App.css";
import { useState } from "react";

function App() {
  const [data] = useState([1, 2, 3, 4]);
  const [selected, setSelected] = useState("");

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          React <code> SELECT RESET </code> demo.
        </p>
        <select value={selected} onChange={(e) => setSelected(e.target.value)}>
          <option>Select</option>
          {data &&
            data.map((d, index) => {
              return <option key={index}>{d}</option>;
            })}
        </select>
        <br />
        <button onClick={() => setSelected("")}>Clear</button>
      </header>
    </div>
  );
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM