How to replace components for custom option content with React-Select?

Sometimes, we want to replace components for custom option content with React-Select.

In this article, we’ll look at how to replace components for custom option content with React-Select.

How to replace components for custom option content with React-Select?

To replace components for custom option content with React-Select, we can set the formatOptionLabel prop to a component that renders the option the way we want.

For instance, we write:

import React from "react";
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>
);

export default function App() {
  return (
    <div>
      <Select
        defaultValue={options[0]}
        formatOptionLabel={formatOptionLabel}
        options={options}
      />
    </div>
  );
}

We have the options array which we use as the options for the Select drop down.

Next, we define the formatOptionLabel component that renders the options the way we want.

The props comes from the entry in the options array.

Then, we add the Select component to App and set the formatOptionLabel prop to formatOptionLabel.

And we set the options prop to options so that the options are rendered and the props are available to formatOptionLabel.

Conclusion

To replace components for custom option content with React-Select, we can set the formatOptionLabel prop to a component that renders the option the way we want.