Micah Bales
Micah Bales

Reputation: 191

How to Implement Multi Select Dropdown in React

I'm looking for a good way to create multi select dropdowns in plain React, without using an additional library.

At present, I’m doing something like this:

<select className='yearlymeeting' multiple={true}>
    <option value=''>Yearly Meeting</option>
    {
        this.state.meeting.yearly_meeting.map((m: Meeting, i: number) => {
            return (
                <option
                    value={m.title}
                    key={i}
                    selected={this.state.selectedTitles.yearlyMeetingTitles.includes(m.title) ? true : false}>
                    {m.title}
                </option>
             );
         })
     }
</select>

This code "works", but I'm getting this warning:

Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.

Upvotes: 0

Views: 5515

Answers (2)

Egor Nikitin
Egor Nikitin

Reputation: 41

From react docs -

You can pass an array into the value attribute, allowing you to select multiple options in a select tag:

<select multiple={true} value={['B', 'C']}>

I think you just need to pass your selected items array to value prop of select element.

Upvotes: 3

MMH
MMH

Reputation: 786

Instead of checking conditions and setting "selected" props in the "option" element, directly set the value in the "select" element. The warning should go away.

<select className='yearlymeeting' multiple={true} 
value={this.state.selectedTitles.yearlyMeetingTitles}>
<option value=''>Yearly Meeting</option>
{
    this.state.meeting.yearly_meeting.map((m: Meeting, i: number) => {
        return (
            <option
                value={m.title}
                key={i}
                {m.title}
            </option>
         );
     })
 }
</select>

Upvotes: 2

Related Questions