Categories
React Answers

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

Spread the love

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 components prop to an object with the Option property set to the component we want to render for each option.

For instance, we write:

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

const options = [
  { label: "Apple", value: "apple" },
  { label: "Orange", value: "orange" },
  { label: "Grape", value: "grape" },
  { label: "Pear", value: "pear" },
  { label: "Banana", value: "banana" }
];

const MyOption = (props) => {
  const { innerProps, innerRef } = props;
  return (
    <article ref={innerRef} {...innerProps}>
      <h4>{props.data.label}</h4>
    </article>
  );
};

export default function App() {
  return (
    <form>
      <Select options={options} components={{ Option: MyOption }} />
    </form>
  );
}

We create the MyOption component that destructures the innerProps and innerRef from the props.

Then both are spread as props of the root element of the option component to let us render it as options in the drop down.

props.data has the options object in options.

Next, we set components to an object with the Option property set to MyOption to use MyOption to render each drop down option.

Conclusion

To replace components for custom option content with React-Select, we can set the components prop to an object with the Option property set to the component we want to render for each option.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *