1
votes

I would like to set global style for the react-select. For my understanding I can do 2 ways:

  1. Using className and classNamePrefix and then target elements using CSS.

    PROS: I can use the same style everywhere

    CONS: Every new component must use exactly the same className and classNamePrefix

Example:

className='react-select-container'

classNamePrefix="react-select"

Result:

<div class="react-select-container">
  <div class="react-select__control">
    <div class="react-select__value-container">...</div>
    <div class="react-select__indicators">...</div>
  </div>
  <div class="react-select__menu">
    <div class="react-select__menu-list">
      <div class="react-select__option">...</div>
    </div>
  </div>
</div>
  1. Create external javascript file with "Provided Styles and State"

    PROS: more flexible then CSS

    CONS: Every new component must use style property using imported external file.

Example:

const customStyles = {
  option: (provided, state) => ({
    ...provided,
    borderBottom: '1px dotted pink',
    color: state.isSelected ? 'red' : 'blue',
    padding: 20,
  }),
  control: () => ({
    // none of react-select's styles are passed to <Control />
    width: 200,
  }),
  singleValue: (provided, state) => {
    const opacity = state.isDisabled ? 0.5 : 1;
    const transition = 'opacity 300ms';

    return { ...provided, opacity, transition };
  }
}

  const App = () => (
    <Select
      styles={customStyles}
      options={...}
    />
  );

What is the best way to style multiple react-select components? Will be possible to set style globally and every new react-select component use that style automatically?

1

1 Answers

2
votes

One way to do it is to create your own select component like CustomSelect that you import instead of react-select where you set for one the custom style or theme like:

import React, { Component } from 'react'
import Select from 'react-select'

class CustomSelect extends Component {
  render() {

    const styles = {
      ...
      // what ever you need
    }

    return <Select styles={styles} {...this.props} />
  }
}

export default CustomSelect

I can't really tell if it's the best way or not but I've tried both of it and in a big project with many select it's the easiest way to maintain / modify it. Plus it's really convenient if at some point you need to have custom components.