8

I would like to add placeholder texture to select input using ReactJS, however my current attempt is not working.

My code looks like this:

<Input type="select" placeholder="placeholder">
     <option>First option</option>
     <option>second option</option>
     <option>Thrid option</option>
</Input>

I am expecting the text "placeholder" to show up on the input field before any option has been selected, however the "first option" is showing by default.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65

2 Answers2

18

To achieve the placeholder effect on a <select> element in ReactJS, first add the defaultValue prop to the <select> element and preassign a default value of say the empty string. Then, add a disabled <option> item with a value that matches defaultValue as shown:

<select defaultValue="">
     <option disabled={true} value="">placeholder</option>
     <option>First option</option>
     <option>second option</option>
     <option>Thrid option</option>
</select>

Update

A more robust approach is as follows:

<select defaultValue="">
     <option hidden value="">placeholder</option>
     <option>First option</option>
     <option>second option</option>
     <option>Thrid option</option>
</select>
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
1

You can achieve this functionality using <option value="" hidden> Your Placeholder here </option>

  • This has a better behaviour than the other answer to use `disabled` - in this case, the 'placeholder' is not displayed in the options to choose from, even though its disabled. With this solution, it just isn't there, only the actual selectable values are in the list. – andy mccullough Apr 20 '20 at 19:37