React-Select - Replacing Components for custom option content

user2190690 picture user2190690 · Oct 15, 2018 · Viewed 22.4k times · Source

Using React-Select (version 2) I would like to have custom designed (select) options.

The documentation suggests that Replacing Components would be a method that I could use to achieve this.

Unfortunately I'm unable to find examples that show implementations of this feature.

Is there anyone that could present to me usage of this feature whereby you would have a simple custom option (perhaps a label and value that also includes an SVG graphic to the left of each option label).

Many thanks in advance

Answer

duhseekoh picture duhseekoh · May 16, 2019

For a majority of use cases, you probably don't need to replace the full Option component. If you're looking to stay with the same overall structure and look and feel of the Option, but you want to display several blocks of text, or an image, or some other special treatment to the body of each option, there is an easier way.

That's to use the formatOptionLabel render prop.

import React from "react";
import ReactDOM from "react-dom";
import Select from "react-select";

const options = [
  { value: "Abe", label: "Abe", customAbbreviation: "A" },
  { value: "John", label: "John", customAbbreviation: "J" },
  { value: "Dustin", label: "Dustin", customAbbreviation: "D" }
];

const formatOptionLabel = ({ value, label, customAbbreviation }) => (
  <div style={{ display: "flex" }}>
    <div>{label}</div>
    <div style={{ marginLeft: "10px", color: "#ccc" }}>
      {customAbbreviation}
    </div>
  </div>
);

const CustomControl = () => (
  <Select
    defaultValue={options[0]}
    formatOptionLabel={formatOptionLabel}
    options={options}
  />
);

ReactDOM.render(<CustomControl />, document.getElementById("root"));

https://codesandbox.io/embed/reactselect-formatoptionlabel-bde1q

https://react-select.com/props - search for formatOptionLabel