4

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

2 Answers 2

18

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ok Great !! got it
4

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.