0

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>.
1
  • ok...so what part of that error message isn't clear? And what is your specific question? Did you try doing what the message suggests? Or look in the react docs for <select>? Commented Feb 2, 2019 at 21:02

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thanks! I didn't realize you could pass in an array here. Makes total sense. By the way, here's a link to the documentation: reactjs.org/docs/forms.html
2

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>

1 Comment

Yes, you're correct. Thank you! My blockage here was that it didn't occur to me that I could pass in an array for value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.