samuelli97
samuelli97

Reputation: 71

React virtualized-select custom options styles

I am using the virtualized-select React component. I would like to style the text and background color of the option while it is in the dropdown. For the simple code I have below, the search bar background is red, and the search bar background turns blue when I select option 1, but I would like the background in the option dropdown to be blue. Additionally, the color attribute does not seem to be working at all; are only certain CSS attributes changeable?

render () {

const styles = {
    color: "red",
    background: "red"
};

const options = [
  { label: "One", value: 1 , style: {background: 'blue'}},
  { label: "Two", value: 2 },
  { label: "Three", value: 3}
  //{ label: "Three", value: 3, disabled: true }
  // And so on...
]

return (
  <VirtualizedSelect
    options={options}
    onChange={(selectValue) => this.setState({ selectValue })}
    value={this.state.selectValue}
    placeholder="Search"
    style={styles}
  />
)
  }
}

Upvotes: 0

Views: 5559

Answers (1)

bvaughn
bvaughn

Reputation: 13497

react-virtualized-select does not currently support an option.style property as you've shown in your example, only option.className. (You can see the default optionRender source here.)

If you want custom option-styling like you've described, you'll need to override the optionRenderer as described in the docs. There's an example of this on the react-virtualized-select demo page (under "Custom Option Renderer") and the source code for that example is in the GitHub repo.

I'd recommend forking the default renderer and customizing, like so:

function YourOptionRenderer ({ focusedOption, focusOption, key, labelKey, option, selectValue, style, valueArray }) {
  const className = ['VirtualizedSelectOption']
  if (option === focusedOption) {
    className.push('VirtualizedSelectFocusedOption')
  }
  if (option.disabled) {
    className.push('VirtualizedSelectDisabledOption')
  }
  if (valueArray && valueArray.indexOf(option) >= 0) {
    className.push('VirtualizedSelectSelectedOption')
  }

  const events = option.disabled
    ? {}
    : {
      onClick: () => selectValue(option),
      onMouseEnter: () => focusOption(option)
    }

  return (
    <div
      className={className.join(' ')}
      key={key}
      style={{
        ...style,
        ...option.style,
      }}
      title={option.title}
      {...events}
    >
      {option[labelKey]}
    </div>
  )
}

Alternately, if you'd like to submit a PR to the project to add support for option.style to the default renderer- I'm willing to review it.

Upvotes: 2

Related Questions