I need to clear the selected value of select dropdown as soon as user focus on the select element. I have used the below code but cant figure out what property of select do I need to reset.
<select name="select1" onChange={this.onChangeOption} onFocus={this.handleFocus}>
<option value=''>Please select...</option>
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
<option value='D'>D</option>
</select>
handleFocus(event) {
event.target.select(); // it did not work!!
}
I want the selected value to be Please select...
when the user focuses on the element.
One of the problems with your select element is that it's neither a controlled or an uncontrolled input element. What you want to achieve can be done with both methods, and it looks like you attempted to make a controlled component.
I'll provide a solution for both:
Clearing a controlled
<select>
elementYou need to turn your select element into a controlled component by assigning it a value which is controlled by the state. Then, make your
handleFocus
function reset that state variable.For example:
Clearing an uncontrolled
<select>
elementIf you want to let the DOM manage the select element you could do the following to clear the value whenever the
focus
event is fired.