### Install react-select with npm
Source: https://react-select.com/home
Use this command to install the react-select package using npm.
```bash
npm i --save react-select
```
--------------------------------
### Install react-select with Yarn
Source: https://react-select.com/home
Use this command to install the react-select package using Yarn.
```bash
yarn add react-select
```
--------------------------------
### Advanced Creatable Example with onCreateOption
Source: https://react-select.com/creatable
This example uses the `onCreateOption` prop to handle new options. It simulates a backend delay by disabling the input for a second before adding the new option.
```javascript
import React from 'react';
import Creatable from 'react-select/creatable';
const createOption = (label) => ({
label,
value: label.toLowerCase().replace(/[^a-z0-9]+ /g, '-'),
});
const makeCreatable = (SelectComponent) =>
class MakeCreatable extends React.Component {
state = {
options: colourOptions,
value: undefined,
};
handleChange = (value, actionMeta) => {
if (actionMeta.action === 'create-option') {
this.setState(state => ({
options: [...state.options, createOption(actionMeta.option.label)],
}));
}
};
render() {
return (
);
}
};
const AdvancedCreatable = makeCreatable(Creatable);
export default AdvancedCreatable;
```
--------------------------------
### Creatable Example
Source: https://react-select.com/creatable
Basic example of using the Creatable component for a single select input.
```javascript
import React from 'react';
import Creatable from 'react-select/creatable';
const CreatableSingle = () => (
console.log(colourOptions)}
isMulti />
);
export default CreatableSingle;
```
--------------------------------
### Creatable Multiselect Example
Source: https://react-select.com/creatable
Example demonstrating the Creatable component used for a multiselect input.
```javascript
import React from 'react';
import Creatable from 'react-select/creatable';
const CreatableMulti = () => (
console.log(colourOptions)}
isMulti />
);
export default CreatableMulti;
```
--------------------------------
### Basic Select Example
Source: https://react-select.com/advanced
A fundamental example of the `Select` component, showcasing basic usage with options and a clearable interface.
```jsx
import Select from 'react-select';
const colourOptions = [
{ value: 'ocean', label: 'Ocean' },
{ value: 'blue', label: 'Blue' },
{ value: 'purple', label: 'Purple' },
{ value: 'red', label: 'Red' },
{ value: 'orange', label: 'Orange' },
{ value: 'yellow', label: 'Yellow' },
{ value: 'green', label: 'Green' },
{ value: 'white', label: 'White' },
{ value: 'black', label: 'Black' },
];
function SelectBasic() {
return ;
}
```
--------------------------------
### Creatable Select Example
Source: https://react-select.com/advanced
Demonstrates the `Creatable` select component, which allows users to create new options on the fly. It requires importing `Creatable` from `react-select/creatable`.
```jsx
import CreatableSelect from 'react-select/creatable';
function CreatableSingle() {
return ;
}
```
--------------------------------
### Async Select Example
Source: https://react-select.com/advanced
Illustrates the `Async` select component for fetching options asynchronously. It requires importing `Async` from `react-select/async` and providing an `loadOptions` function.
```jsx
import AsyncSelect from 'react-select/async';
function GitHubUser() {
return (
);
}
```
--------------------------------
### Async Creatable Example
Source: https://react-select.com/creatable
Example showcasing the combined asynchronous and creatable variant of the select input. Imported from `react-select/async-creatable`.
```javascript
import React from 'react';
import AsyncCreatableSelect from 'react-select/async-creatable';
const filterColors = (inputValue) => {
return colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
};
const promiseOptions = inputValue =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
const AsyncCreatable = () => (
);
export default AsyncCreatable;
```
--------------------------------
### Custom Filter Logic with createFilter
Source: https://react-select.com/advanced
Demonstrates how to use the `createFilter` function to customize the filtering logic for React Select. This example shows how to create a filter with specific configurations.
```javascript
Ocean
Ignore CaseIgnore AccentsTrimMatch from the start
```
--------------------------------
### Custom Option Component Styling
Source: https://react-select.com/styles
Example of creating a custom Option component using cx and getStyles for dynamic styling based on component state like isDisabled, isFocused, and isSelected.
```javascript
import { css } from 'emotion';
const CustomOption = ({ cx, children, getStyles, innerRef, ...props }) => (
{children}
)
```
--------------------------------
### Date Picker Select Recipe
Source: https://react-select.com/advanced
This example demonstrates how to configure react-select to function as a date picker using custom components and functions. It supports natural language date inputs.
```jsx
function DatePickerSelect() {
return (
)
}
```
--------------------------------
### Custom Option Component with Emotion 9
Source: https://react-select.com/upgrade
Example of creating a custom option component using Emotion 9 before upgrading to react-select v3.0.0.
```jsx
import { css } from 'emotion'
const customOption = ({ cx, className, getStyles, _ }) =>
```
--------------------------------
### getStyles
Source: https://react-select.com/props
Get the styles of a particular part of the select. Pass in the name of the property as the first argument, and the current props as the second argument. See the `styles` object for the properties available.
```APIDOC
## getStyles
### Description
Get the styles of a particular part of the select. Pass in the name of the property as the first argument, and the current props as the second argument. See the `styles` object for the properties available.
### Signature
`(...) => ...`
```
--------------------------------
### Custom Option Component with Emotion 10
Source: https://react-select.com/upgrade
Example of creating a custom option component using Emotion 10 after upgrading to react-select v3.0.0. This version leverages the jsx pragma for emotion.
```jsx
/** @jsx jsx */
import { jsx } from '@emotion/core';
const customOption = ({ cx, className, getStyles, _ }) =>
```
--------------------------------
### Custom filterOption Function
Source: https://react-select.com/advanced
Provides a custom `filterOption` function to control how options are filtered. This example ensures that new options can be created and that existing options containing the input are always displayed.
```javascript
const filterOption = (candidate, input) => {
return candidate.data.__isNew__ || candidate.label.includes(input);
};
```
--------------------------------
### Define Custom Option Component in React Select
Source: https://react-select.com/components
Example of creating a custom Option component for React Select. Ensure to assign the innerRef prop to the relevant DOM element and spread innerProps.
```jsx
const CustomOption = ({ innerRef, innerProps }) => (
)
```
--------------------------------
### Get Styles for Components
Source: https://react-select.com/styles
The getStyles method retrieves style objects for specific components. It takes a component key (e.g., 'option') and a props object containing relevant state values.
```javascript
(key: string, props: Object) => stylesObject;
```
--------------------------------
### Custom Option Component with InnerRef
Source: https://react-select.com/props
Example of a custom option component that utilizes `innerRef` to assign a DOM element reference. This is useful for managing internal component behavior.
```jsx
const CustomOptionComponent = ({ innerProps, innerRef }) =>
()
```
--------------------------------
### `options`
Source: https://react-select.com/props
An array of options that populate the select menu.
```APIDOC
## `options`
### Description
Array of options that populate the select menu.
### Type
ReadonlyArray>
```
--------------------------------
### Import Animated Components Wrapper
Source: https://react-select.com/home
Import the `makeAnimated` function to create animated wrappers around components. If no arguments are provided, built-in components are wrapped.
```javascript
import makeAnimated from 'react-select/animated';
```
--------------------------------
### Input and Option Handling
Source: https://react-select.com/props
Props for managing the input element, options, and related events.
```APIDOC
## `name`
### Description
Name of the HTML Input (optional - without this, no input will be rendered).
### Type
string
## `noOptionsMessage`
### Description
Text to display when there are no options.
### Type
(...) => ...
## `onBlur`
### Description
Handle blur events on the control.
### Type
(...) => void
## `onFocus`
### Description
Handle focus events on the control.
### Type
(...) => void
## `onKeyDown`
### Description
Handle key down events on the select.
### Type
(...) => void
## `onMenuScrollToTop`
### Description
Fired when the user scrolls to the top of the menu.
### Type
(...) => void
## `onMenuScrollToBottom`
### Description
Fired when the user scrolls to the bottom of the menu.
### Type
(...) => void
## `options`
### Description
Array of options that populate the select menu.
### Type
ReadonlyArray>
## `pageSize`
### Description
Number of options to jump in menu when page{up|down} keys are used.
### Type
number
## `placeholder`
### Description
Placeholder for the select value.
### Type
ReactNode One of < null, string, number, boolean, {}, ReactElement{...}, ReactNodeArray{...}, ReactPortal{...} >
## `screenReaderStatus`
### Description
Status to relay to screen readers.
### Type
(...) => string
```
--------------------------------
### Importing Async Component (v2)
Source: https://react-select.com/upgrade
Demonstrates the previous import method for the Async component in react-select versions prior to v3.0.0.
```javascript
import { Async } from 'react-select'
```
```javascript
import Async from 'react-select/lib/Async'
```
--------------------------------
### Import AsyncSelect Component
Source: https://react-select.com/home
Use the `AsyncSelect` component to load options from a remote source as the user types. This is useful for handling large datasets or dynamic options.
```javascript
import AsyncSelect from 'react-select/async';
```
--------------------------------
### options
Source: https://react-select.com/props
The options to display in the select component.
```APIDOC
## options
### Description
The options to display in the select component.
### Type
`ReadonlyArray>`
```
--------------------------------
### Styling and Theming
Source: https://react-select.com/props
Props for customizing the visual appearance and theme of the select component.
```APIDOC
## `styles`
### Description
Style modifier methods. A basic example can be found at the bottom of the Replacing builtins documentation.
### Type
StylesConfig{...}
## `theme`
### Description
Theme modifier method.
### Type
One of < Theme{...}, (...) => ... >
```
--------------------------------
### `menuIsOpen`
Source: https://react-select.com/props
Programmatically controls whether the menu is open.
```APIDOC
## `menuIsOpen`
### Description
Whether the menu is open.
### Type
boolean
```
--------------------------------
### theme
Source: https://react-select.com/props
The theme object for styling the select component.
```APIDOC
## theme
### Description
The theme object for styling the select component.
### Type
`Theme{...}`
```
--------------------------------
### Importing Async Component (v3)
Source: https://react-select.com/upgrade
Shows the new import path for the Async component in react-select v3.0.0, utilizing the separate entry point.
```javascript
import AsyncSelect from 'react-select/async'
```
--------------------------------
### `menuShouldScrollIntoView`
Source: https://react-select.com/props
Ensures the menu scrolls into view when it opens.
```APIDOC
## `menuShouldScrollIntoView`
### Description
Whether the menu should be scrolled into view when it opens.
### Type
boolean
```
--------------------------------
### `minMenuHeight`
Source: https://react-select.com/props
Sets the minimum height of the menu before it flips to the opposite placement.
```APIDOC
## `minMenuHeight`
### Description
Minimum height of the menu before flipping.
### Type
number
```
--------------------------------
### about
Source: https://react-select.com/props
Provides a URI to a document that defines the element's properties.
```APIDOC
## about
### Description
URI defining the element's properties.
### Type
`string`
```
--------------------------------
### Menu Properties
Source: https://react-select.com/props
Configuration options related to the dropdown menu's appearance and behavior.
```APIDOC
## `menuPosition`
### Description
The CSS position value of the menu, when "fixed" extra layout management is required.
### Type
One of < "absolute", "fixed" >
## `menuPortalTarget`
### Description
Whether the menu should use a portal, and where it should attach. An example can be found in the Portaling documentation.
### Type
One of < null, HTMLElement{...} >
## `menuShouldBlockScroll`
### Description
Whether to block scroll events when the menu is open.
### Type
boolean
## `menuShouldScrollIntoView`
### Description
Whether the menu should be scrolled into view when it opens.
### Type
boolean
```
--------------------------------
### Popout Select Recipe
Source: https://react-select.com/advanced
A recipe for using select in limited space, disabling `controlShouldRenderValue`. It's recommended to also disable `isClearable` and `backspaceRemovesValue` when using this pattern.
```jsx
function PopoutSelect() {
return (
)
}
```
--------------------------------
### MenuList Props
Source: https://react-select.com/props
Props to be passed to the menu-list wrapper.
```APIDOC
## MenuList Props
### Description
Props to be passed to the menu-list wrapper.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **innerProps** (DetailedHTMLProps Intersection<...>) - Required - Props to be passed to the menu-list wrapper.
- **className** (string) - Optional - CSS class name for the wrapper.
- **clearValue** (() => void) - Required - Function to clear the current selection.
- **cx** ((...) => string) - Required - Function to generate CSS class names.
- **getStyles** (((...) => ...) - Required - Function to get styles for a specific part of the select component.
- **getClassNames** (((...) => ...) - Required - Function to get class names for specific parts.
- **getValue** (() => ReadonlyArray<...>) - Required - Function to get the current selected value(s).
- **hasValue** (boolean) - Required - Indicates if the select component has a value.
- **isMulti** (boolean) - Required - Indicates if the select component is in multi-select mode.
- **isRtl** (boolean) - Required - Indicates if the select component is in right-to-left mode.
- **options** (ReadonlyArray>) - Required - The available options for the select component.
- **selectOption** ((...) => void) - Required - Function to select an option.
- **selectProps** (Props{...}) - Required - Props passed down from the main select component.
- **setValue** ((...) => void) - Required - Function to set the value of the select component.
- **theme** (Theme{...}) - Required - The theme object for styling.
```
--------------------------------
### `openMenuOnFocus`
Source: https://react-select.com/props
Controls whether the menu opens automatically when the Select component receives focus.
```APIDOC
## `openMenuOnFocus`
### Description
Allows control of whether the menu is opened when the Select is focused.
### Type
boolean
```
--------------------------------
### Input Props
Source: https://react-select.com/props
Props for the Input component, which handles user input.
```APIDOC
## Input
### Props
* **innerRef** ((...) => void) - Reference to the internal element.
* **isHidden** (boolean) - Required - Set whether the input should be visible. Does not affect input size.
* **isDisabled** (boolean) - Whether the input is disabled.
* **form** (string) - The ID of the form that the input belongs to.
* **inputClassName** (string) - Set className for the input element.
* **accept** (string)
* **alt** (string)
* **autoComplete** (string)
* **capture** (string | boolean)
* **checked** (boolean)
* **disabled** (boolean)
* **formAction** (string)
* **formEncType** (string)
* **formMethod** (string)
* **formNoValidate** (boolean)
* **formTarget** (string)
* **height** (string | number)
* **list** (string)
* **max** (string | number)
* **maxLength** (number)
* **min** (string | number)
* **minLength** (number)
* **multiple** (boolean)
* **name** (string)
* **pattern** (string)
* **placeholder** (string)
* **readOnly** (boolean)
* **required** (boolean)
* **size** (number)
* **src** (string)
* **step** (string | number)
* **type** (One of <"number", "button", "time", "image", "text", "hidden", "month", "password", "Intersection<...>", "checkbox", "radio", "color", "reset", "range", "search", "date", "datetime-local", "email", "file", "submit", "tel", "url", "week">)
* **value** (string | number | ReadonlyArray)
* **width** (string | number)
```
--------------------------------
### `isMulti`
Source: https://react-select.com/props
Enables support for selecting multiple options.
```APIDOC
## `isMulti`
### Description
Support multiple selected options.
### Type
IsMulti
```
--------------------------------
### `defaultMenuIsOpen`
Source: https://react-select.com/props
Sets the default state of the menu to be open.
```APIDOC
## `defaultMenuIsOpen`
### Description
Sets the default state of the menu to be open.
### Type
boolean
```
--------------------------------
### `pageSize`
Source: https://react-select.com/props
Determines the number of options to jump when using page up/down keys in the menu.
```APIDOC
## `pageSize`
### Description
Number of options to jump in menu when page{up|down} keys are used.
### Type
number
```
--------------------------------
### style
Source: https://react-select.com/props
Applies inline styles to the element.
```APIDOC
## style
### Description
Applies inline CSS styles to the element.
### Type
`CSSProperties`
```
--------------------------------
### Basic React Select Usage
Source: https://react-select.com/home
Import the default export and render the Select component in your React application. Ensure you provide an array of options with 'value' and 'label' properties.
```jsx
import React from 'react'
import Select from 'react-select'
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const MyComponent = () => (
)
```
--------------------------------
### `placeholder`
Source: https://react-select.com/props
Placeholder text displayed when no option is selected.
```APIDOC
## `placeholder`
### Description
Placeholder for the select value.
### Type
ReactNode One of <
null,
string,
number,
boolean,
{...},
ReactElement{...},
ReactNodeArray{...},
ReactPortal{...}
>
```
--------------------------------
### accessKey
Source: https://react-select.com/props
Provides a shortcut to access an element using the keyboard.
```APIDOC
## accessKey
### Description
Provides a keyboard shortcut to access the element.
### Type
`string`
```
--------------------------------
### Server-Side Rendering with Emotion
Source: https://react-select.com/advanced
React-select uses Emotion for styling, which supports zero-config server-side rendering. Ensure you call `renderToString` from `react-dom/server` or use a framework like Next.js or Gatsby.
```javascript
import { renderToString } from 'react-dom/server'
import App from './App'
const html = renderToString()
```
--------------------------------
### Import Creatable Component
Source: https://react-select.com/home
The `Creatable` component allows users to create new options in addition to selecting existing ones. This is useful for scenarios where users might need to add new values to a list.
```javascript
import Creatable from 'react-select/creatable';
```
--------------------------------
### is
Source: https://react-select.com/props
Specifies that a standard HTML element should behave like a defined custom built-in element.
```APIDOC
## is
### Description
Specifies that a standard HTML element should behave like a defined custom built-in element.
### Type
`string`
```
--------------------------------
### `openMenuOnClick`
Source: https://react-select.com/props
Controls whether the menu opens automatically when the Select component is clicked.
```APIDOC
## `openMenuOnClick`
### Description
Allows control of whether the menu is opened when the Select is clicked.
### Type
boolean
```
--------------------------------
### `getOptionLabel`
Source: https://react-select.com/props
Resolves option data to a string for display as the label, crucial for filtering and screen reader support.
```APIDOC
## `getOptionLabel`
### Description
Resolves option data to a string to be displayed as the label by components.
Note: Failure to resolve to a string type can interfere with filtering and screen reader support.
### Type
(...) => string
```
--------------------------------
### Import Async Component
Source: https://react-select.com/async
Import the Async component and the useAsync hook from 'react-select/async'. This is the primary import for asynchronous functionality.
```javascript
import Async, { useAsync } from 'react-select/async';
```
--------------------------------
### inputMode
Source: https://react-select.com/props
Hints at the type of data that might be entered by the user.
```APIDOC
## inputMode
### Description
Hints at the type of data that might be entered by the user.
### Type
`"text" | "none" | "decimal" | "search" | "email" | "tel" | "url" | "numeric"`
```
--------------------------------
### Wrapping React Select with Generics
Source: https://react-select.com/typescript
Demonstrates how to create a flexible wrapper component for React Select that re-declares and forwards the generics, ensuring type safety for custom implementations.
```typescript
function CustomSelect<
Option,
IsMulti extends boolean = false,
Group extends GroupBase