Jay Derus
Jay Derus

Reputation: 25

How can I apply default styles for react-select when defining a custom Option Component?

I am a React noob, and also new to react-select (v2).

I think our scenario is fairly simple. We are pulling data from Azure Search (facets), and want to bind to a slightly customized react-select control.

We want to:

  1. Add in a badge/pill to display counts in the dropdown.
  2. Avoid looping through returned data to dupe value and label in react-select options.

We have gotten most of the way there, with help from this example (which was more helpful than the official docs IMO) : React-Select - Replacing Components for custom option content. The only thing missing is applying the default react-select styles (eg: for hover).

Data Example:

const myOptions = [
    { value: 'foo', count: 100 },
    { value: 'bar', count: 200 },

];

Custom Control Example:

const CustomOption = (props:any) => {
    const { innerProps, innerRef } = props;
    return (
        <article ref={innerRef} {...innerProps} >
            <div style={{display:"inline-block"}}>{props.data.value}</div>
            <span className="badge badge-light float-right" style={{display:"inline-block"}}>{props.data.count} </span>
        </article>
    );
};

Is there a way to reuse the default react-select styles? Am I missing something in the docs?

Upvotes: 1

Views: 2141

Answers (1)

Laura
Laura

Reputation: 8630

You're really cloth but let me show you how to keep the original styles and behaviour of react-select.

Instead of declaring a new container for your Option component you need to use the original one and only edit the content like this:

const Option = props => {
  return (
    <components.Option {...props}>
      <div style={{ display: "inline-block" }}>{props.data.value}</div>
      <span
        className="badge badge-light float-right"
        style={{ display: "inline-block" }}
      >
        {props.data.count}{" "}
      </span>
    </components.Option>
  );
};

Here a live example of your code updated.

Upvotes: 1

Related Questions