user10398929
user10398929

Reputation:

ReactJS: how to display placeholder on select input

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.

Upvotes: 9

Views: 13831

Answers (2)

Dacre Denny
Dacre Denny

Reputation: 30360

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>

Upvotes: 19

muhammad usman
muhammad usman

Reputation: 37

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

Upvotes: 1

Related Questions