How to pass array into ReactSelect

Viewed 514

I have an array of strings named times. Which is formatted like this: enter image description here

I passed it onto a component as props but I am having a hard time passing it onto the ReactSelect component.

const TimeInput=(
            <div>
                <ReactSelect
                        className='react-select react-select-top'
                        classNamePrefix='react-select'
                        id='displayLanguage'
                        menuIsOpen={this.state.openMenu}
                        menuPortalTarget={document.body}
                        styles={reactStyles}
                        **options={this.props.times}**
                        clearable={false}
                        onKeyDown={this.handleKeyDown}
                        onMenuClose={this.handleMenuClose}
                        onMenuOpen={this.handleMenuOpen}
                        aria-labelledby='changeInterfaceLanguageLabel'
                    />
            </div>
        )

I get this error when I try to pass the times array into ReactSelect (please ignore the errors after that as those are functions I have not worked on yet ie. handleMenuClose:

enter image description here

1 Answers

The options prop takes in an array of JSON objects with the keys value and label, so you need to convert your array of times into that format.

One way to do that is mapping

// Before your render function

const timeOptions = this.props.times.map((timeString) => {
  // Ideally you can change the value to something different that is easier to keep track of like the UTC offset
  return {
      value: timeString,
      label: timeString
    }
  }
);

// In render function
// Now pass in timeOptions as the prop for your ReactSelect
...
<ReactSelect
...
  options={timeOptions}
...>

Related