简体   繁体   中英

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>.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM