1 | [![NPM](https://img.shields.io/npm/v/react-select.svg)](https://www.npmjs.com/package/react-select)
|
2 | [![Build Status](https://travis-ci.org/JedWatson/react-select.svg?branch=master)](https://travis-ci.org/JedWatson/react-select)
|
3 | [![Coverage Status](https://coveralls.io/repos/JedWatson/react-select/badge.svg?branch=master&service=github)](https://coveralls.io/github/JedWatson/react-select?branch=master)
|
4 | [![Supported by Thinkmill](https://thinkmill.github.io/badge/heart.svg)](http://thinkmill.com.au/?utm_source=github&utm_medium=badge&utm_campaign=react-select)
|
5 |
|
6 | React-Select
|
7 | ============
|
8 |
|
9 | A Select control built with and for [React](http://facebook.github.io/react/index.html). Initially built for use in [KeystoneJS](http://www.keystonejs.com).
|
10 |
|
11 |
|
12 | ## New version 1.0.0-rc
|
13 |
|
14 | I've nearly completed a major rewrite of this component (see issue [#568](https://github.com/JedWatson/react-select/issues/568) for details and progress). The new code has been merged into `master`, and `react-select@1.0.0-rc` has been published to npm and bower.
|
15 |
|
16 | 1.0.0 has some breaking changes. The documentation is still being updated for the new API; notes on the changes can be found in [CHANGES.md](https://github.com/JedWatson/react-select/blob/master/CHANGES.md) and will be finalised into [HISTORY.md](https://github.com/JedWatson/react-select/blob/master/HISTORY.md) soon.
|
17 |
|
18 | Testing, feedback and PRs for the new version are appreciated.
|
19 |
|
20 |
|
21 | ## Demo & Examples
|
22 |
|
23 | Live demo: [jedwatson.github.io/react-select](http://jedwatson.github.io/react-select/)
|
24 |
|
25 | The live demo is still running `v0.9.1`.
|
26 |
|
27 | To build the **new 1.0.0** examples locally, clone this repo then run:
|
28 |
|
29 | ```javascript
|
30 | npm install
|
31 | npm start
|
32 | ```
|
33 |
|
34 | Then open [`localhost:8000`](http://localhost:8000) in a browser.
|
35 |
|
36 |
|
37 | ## Installation
|
38 |
|
39 | The easiest way to use React-Select is to install it from NPM and include it in your own React build process (using [Browserify](http://browserify.org), etc).
|
40 |
|
41 | ```javascript
|
42 | npm install react-select --save
|
43 | ```
|
44 |
|
45 | At this point you can import react-select and its styles in your application as follows:
|
46 |
|
47 | ```js
|
48 | import Select from 'react-select';
|
49 |
|
50 | // Be sure to include styles at some point, probably during your bootstrapping
|
51 | import 'react-select/dist/react-select.css';
|
52 | ```
|
53 |
|
54 | You can also use the standalone build by including `react-select.js` and `react-select.css` in your page. (If you do this though you'll also need to include the dependencies.) For example:
|
55 | ```html
|
56 | <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
|
57 | <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
|
58 | <script src="https://unpkg.com/classnames/index.js"></script>
|
59 | <script src="https://unpkg.com/react-input-autosize/dist/react-input-autosize.js"></script>
|
60 | <script src="https://unpkg.com/react-select/dist/react-select.js"></script>
|
61 |
|
62 | <link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css">
|
63 | ```
|
64 |
|
65 |
|
66 | ## Usage
|
67 |
|
68 | React-Select generates a hidden text field containing the selected value, so you can submit it as part of a standard form. You can also listen for changes with the `onChange` event property.
|
69 |
|
70 | Options should be provided as an `Array` of `Object`s, each with a `value` and `label` property for rendering and searching. You can use a `disabled` property to indicate whether the option is disabled or not.
|
71 |
|
72 | The `value` property of each option should be set to either a string or a number.
|
73 |
|
74 | When the value is changed, `onChange(selectedValueOrValues)` will fire.
|
75 |
|
76 | ```javascript
|
77 | var Select = require('react-select');
|
78 |
|
79 | var options = [
|
80 | { value: 'one', label: 'One' },
|
81 | { value: 'two', label: 'Two' }
|
82 | ];
|
83 |
|
84 | function logChange(val) {
|
85 | console.log("Selected: " + val);
|
86 | }
|
87 |
|
88 | <Select
|
89 | name="form-field-name"
|
90 | value="one"
|
91 | options={options}
|
92 | onChange={logChange}
|
93 | />
|
94 | ```
|
95 |
|
96 | ### Multiselect options
|
97 |
|
98 | You can enable multi-value selection by setting `multi={true}`. In this mode:
|
99 |
|
100 | * Selected options will be removed from the dropdown menu
|
101 | * The selected values are submitted in multiple `<input type="hidden">` fields, use `joinValues` to submit joined values in a single field instead
|
102 | * The values of the selected items are joined using the `delimiter` prop to create the input value when `joinValues` is true
|
103 | * A simple value, if provided, will be split using the `delimiter` prop
|
104 | * The `onChange` event provides an array of selected options _or_ a comma-separated string of values (eg `"1,2,3"`) if `simpleValue` is true
|
105 | * By default, only options in the `options` array can be selected. Setting `allowCreate` to true allows new options to be created if they do not already exist. *NOTE:* `allowCreate` is not implemented in `1.0.0-beta`, if you need this option please stay on `0.9.x`.
|
106 | * By default, selected options can be cleared. To disable the possibility of clearing a particular option, add `clearableValue: false` to that option:
|
107 | ```javascript
|
108 | var options = [
|
109 | { value: 'one', label: 'One' },
|
110 | { value: 'two', label: 'Two', clearableValue: false }
|
111 | ];
|
112 | ```
|
113 | Note: the `clearable` prop of the Select component should also be set to `false` to prevent allowing clearing all fields at once
|
114 |
|
115 | ### Async options
|
116 |
|
117 | If you want to load options asynchronously, instead of providing an `options` Array, provide a `loadOptions` Function.
|
118 |
|
119 | The function takes two arguments `String input, Function callback`and will be called when the input text is changed.
|
120 |
|
121 | When your async process finishes getting the options, pass them to `callback(err, data)` in a Object `{ options: [] }`.
|
122 |
|
123 | The select control will intelligently cache options for input strings that have already been fetched. The cached result set will be filtered as more specific searches are input, so if your async process would only return a smaller set of results for a more specific query, also pass `complete: true` in the callback object. Caching can be disabled by setting `cache` to `false` (Note that `complete: true` will then have no effect).
|
124 |
|
125 | Unless you specify the property `autoload={false}` the control will automatically load the default set of options (i.e. for `input: ''`) when it is mounted.
|
126 |
|
127 | ```javascript
|
128 | var Select = require('react-select');
|
129 |
|
130 | var getOptions = function(input, callback) {
|
131 | setTimeout(function() {
|
132 | callback(null, {
|
133 | options: [
|
134 | { value: 'one', label: 'One' },
|
135 | { value: 'two', label: 'Two' }
|
136 | ],
|
137 | // CAREFUL! Only set this to true when there are no more options,
|
138 | // or more specific queries will not be sent to the server.
|
139 | complete: true
|
140 | });
|
141 | }, 500);
|
142 | };
|
143 |
|
144 | <Select.Async
|
145 | name="form-field-name"
|
146 | loadOptions={getOptions}
|
147 | />
|
148 | ```
|
149 |
|
150 | ### Async options with Promises
|
151 |
|
152 | `loadOptions` supports Promises, which can be used in very much the same way as callbacks.
|
153 |
|
154 | Everything that applies to `loadOptions` with callbacks still applies to the Promises approach (e.g. caching, autoload, ...)
|
155 |
|
156 | An example using the `fetch` API and ES6 syntax, with an API that returns an object like:
|
157 |
|
158 | ```javascript
|
159 | import Select from 'react-select';
|
160 |
|
161 | /*
|
162 | * assuming the API returns something like this:
|
163 | * const json = [
|
164 | * { value: 'one', label: 'One' },
|
165 | * { value: 'two', label: 'Two' }
|
166 | * ]
|
167 | */
|
168 |
|
169 | const getOptions = (input) => {
|
170 | return fetch(`/users/${input}.json`)
|
171 | .then((response) => {
|
172 | return response.json();
|
173 | }).then((json) => {
|
174 | return { options: json };
|
175 | });
|
176 | }
|
177 |
|
178 | <Select.Async
|
179 | name="form-field-name"
|
180 | value="one"
|
181 | loadOptions={getOptions}
|
182 | />
|
183 | ```
|
184 |
|
185 | ### Async options loaded externally
|
186 |
|
187 | If you want to load options asynchronously externally from the `Select` component, you can have the `Select` component show a loading spinner by passing in the `isLoading` prop set to `true`.
|
188 |
|
189 | ```javascript
|
190 | var Select = require('react-select');
|
191 |
|
192 | var isLoadingExternally = true;
|
193 |
|
194 | <Select
|
195 | name="form-field-name"
|
196 | isLoading={isLoadingExternally}
|
197 | ...
|
198 | />
|
199 | ```
|
200 |
|
201 | ### User-created tags
|
202 |
|
203 | The `Creatable` component enables users to create new tags within react-select.
|
204 | It decorates a `Select` and so it supports all of the default properties (eg single/multi mode, filtering, etc) in addition to a couple of custom ones (shown below).
|
205 | The easiest way to use it is like so:
|
206 |
|
207 | ```js
|
208 | import { Creatable } from 'react-select';
|
209 |
|
210 | function render (selectProps) {
|
211 | return <Creatable {...selectProps} />;
|
212 | };
|
213 | ```
|
214 |
|
215 | ##### Creatable properties
|
216 |
|
217 | Property | Type | Description
|
218 | :---|:---|:---
|
219 | `isOptionUnique` | function | Searches for any matching option within the set of options. This function prevents duplicate options from being created. By default this is a basic, case-sensitive comparison of label and value. Expected signature: `({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean` |
|
220 | `isValidNewOption` | function | Determines if the current input text represents a valid option. By default any non-empty string will be considered valid. Expected signature: `({ label: string }): boolean` |
|
221 | `newOptionCreator` | function | Factory to create new option. Expected signature: `({ label: string, labelKey: string, valueKey: string }): Object` |
|
222 | `shouldKeyDownEventCreateNewOption` | function | Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option. ENTER, TAB and comma keys create new options by dfeault. Expected signature: `({ keyCode: number }): boolean` |
|
223 |
|
224 | ### Filtering options
|
225 |
|
226 | You can control how options are filtered with the following properties:
|
227 |
|
228 | * `matchPos`: `"start"` or `"any"`: whether to match the text entered at the start or any position in the option value
|
229 | * `matchProp`: `"label"`, `"value"` or `"any"`: whether to match the value, label or both values of each option when filtering
|
230 | * `ignoreCase`: `Boolean`: whether to ignore case or match the text exactly when filtering
|
231 |
|
232 | `matchProp` and `matchPos` both default to `"any"`.
|
233 | `ignoreCase` defaults to `true`.
|
234 |
|
235 | #### Advanced filters
|
236 |
|
237 | You can also completely replace the method used to filter either a single option, or the entire options array (allowing custom sort mechanisms, etc.)
|
238 |
|
239 | * `filterOption`: `function(Object option, String filter)` returns `Boolean`. Will override `matchPos`, `matchProp` and `ignoreCase` options.
|
240 | * `filterOptions`: `function(Array options, String filter, Array currentValues)` returns `Array filteredOptions`. Will override `filterOption`, `matchPos`, `matchProp` and `ignoreCase` options.
|
241 |
|
242 | For multi-select inputs, when providing a custom `filterOptions` method, remember to exclude current values from the returned array of options.
|
243 |
|
244 | #### Filtering large lists
|
245 |
|
246 | The default `filterOptions` method scans the options array for matches each time the filter text changes.
|
247 | This works well but can get slow as the options array grows to several hundred objects.
|
248 | For larger options lists a custom filter function like [`react-select-fast-filter-options`](https://github.com/bvaughn/react-select-fast-filter-options) will produce better results.
|
249 |
|
250 | ### Effeciently rendering large lists with windowing
|
251 |
|
252 | The `menuRenderer` property can be used to override the default drop-down list of options.
|
253 | This should be done when the list is large (hundreds or thousands of items) for faster rendering.
|
254 | Windowing libraries like [`react-virtualized`](https://github.com/bvaughn/react-virtualized) can then be used to more efficiently render the drop-down menu like so.
|
255 | The easiest way to do this is with the [`react-virtualized-select`](https://github.com/bvaughn/react-virtualized-select/) HOC.
|
256 | This component decorates a `Select` and uses the react-virtualized `VirtualScroll` component to render options.
|
257 | Demo and documentation for this component are available [here](https://bvaughn.github.io/react-virtualized-select/).
|
258 |
|
259 | You can also specify your own custom renderer.
|
260 | The custom `menuRenderer` property accepts the following named parameters:
|
261 |
|
262 | | Parameter | Type | Description |
|
263 | |:---|:---|:---|
|
264 | | focusedOption | `Object` | The currently focused option; should be visible in the menu by default. |
|
265 | | focusOption | `Function` | Callback to focus a new option; receives the option as a parameter. |
|
266 | | labelKey | `String` | Option labels are accessible with this string key. |
|
267 | | options | `Array<Object>` | Ordered array of options to render. |
|
268 | | selectValue | `Function` | Callback to select a new option; receives the option as a parameter. |
|
269 | | valueArray | `Array<Object>` | Array of currently selected options. |
|
270 |
|
271 | ### Updating input values with onInputChange
|
272 |
|
273 | You can manipulate the input using the onInputChange and returning a new value.
|
274 |
|
275 | ```js
|
276 | function cleanInput(inputValue) {
|
277 | // Strip all non-number characters from the input
|
278 | return inputValue.replace(/[^0-9]/g, "");
|
279 | }
|
280 |
|
281 | <Select
|
282 | name="form-field-name"
|
283 | onInputChange={cleanInput}
|
284 | />
|
285 | ```
|
286 |
|
287 | ### Overriding default key-down behavior with onInputKeyDown
|
288 |
|
289 | `Select` listens to `keyDown` events to select items, navigate drop-down list via arrow keys, etc.
|
290 | You can extend or override this behavior by providing a `onInputKeyDown` callback.
|
291 |
|
292 | ```js
|
293 | function onInputKeyDown(event) {
|
294 | switch (event.keyCode) {
|
295 | case 9: // TAB
|
296 | // Extend default TAB behavior by doing something here
|
297 | break;
|
298 | case 13: // ENTER
|
299 | // Override default ENTER behavior by doing stuff here and then preventing default
|
300 | event.preventDefault();
|
301 | break;
|
302 | }
|
303 | }
|
304 |
|
305 | <Select
|
306 | {...otherProps}
|
307 | onInputKeyDown={onInputKeyDown}
|
308 | />
|
309 | ```
|
310 |
|
311 | ### Further options
|
312 |
|
313 |
|
314 | Property | Type | Default | Description
|
315 | :-----------------------|:--------------|:--------------|:--------------------------------
|
316 | addLabelText | string | 'Add "{label}"?' | text to display when `allowCreate` is true
|
317 | autoBlur | bool | false | Blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices
|
318 | autofocus | bool | undefined | autofocus the component on mount
|
319 | autoload | bool | true | whether to auto-load the default async options set
|
320 | autosize | bool | true | If enabled, the input will expand as the length of its value increases
|
321 | backspaceRemoves | bool | true | whether pressing backspace removes the last item when there is no input value
|
322 | cache | bool | true | enables the options cache for `asyncOptions` (default: `true`)
|
323 | className | string | undefined | className for the outer element
|
324 | clearable | bool | true | should it be possible to reset value
|
325 | clearAllText | string | 'Clear all' | title for the "clear" control when `multi` is true
|
326 | clearValueText | string | 'Clear value' | title for the "clear" control
|
327 | resetValue | any | null | value to use when you clear the control
|
328 | delimiter | string | ',' | delimiter to use to join multiple values
|
329 | disabled | bool | false | whether the Select is disabled or not
|
330 | filterOption | func | undefined | method to filter a single option: `function(option, filterString)`
|
331 | filterOptions | func | undefined | method to filter the options array: `function([options], filterString, [values])`
|
332 | ignoreCase | bool | true | whether to perform case-insensitive filtering
|
333 | inputProps | object | {} | custom attributes for the Input (in the Select-control) e.g: `{'data-foo': 'bar'}`
|
334 | isLoading | bool | false | whether the Select is loading externally or not (such as options being loaded)
|
335 | joinValues | bool | false | join multiple values into a single hidden input using the `delimiter`
|
336 | labelKey | string | 'label' | the option property to use for the label
|
337 | loadOptions | func | undefined | function that returns a promise or calls a callback with the options: `function(input, [callback])`
|
338 | matchPos | string | 'any' | (any, start) match the start or entire string when filtering
|
339 | matchProp | string | 'any' | (any, label, value) which option property to filter on
|
340 | menuBuffer | number | 0 | buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
|
341 | menuRenderer | func | undefined | Renders a custom menu with options; accepts the following named parameters: `menuRenderer({ focusedOption, focusOption, options, selectValue, valueArray })`
|
342 | multi | bool | undefined | multi-value input
|
343 | name | string | undefined | field name, for hidden `<input />` tag
|
344 | noResultsText | string | 'No results found' | placeholder displayed when there are no matching search results or a falsy value to hide it
|
345 | onBlur | func | undefined | onBlur handler: `function(event) {}`
|
346 | onBlurResetsInput | bool | true | whether to clear input on blur or not
|
347 | onChange | func | undefined | onChange handler: `function(newValue) {}`
|
348 | onClose | func | undefined | handler for when the menu closes: `function () {}`
|
349 | onCloseResetInput | bool | true | whether to clear input when closing the menu through the arrow
|
350 | onFocus | func | undefined | onFocus handler: `function(event) {}`
|
351 | onInputChange | func | undefined | onInputChange handler: `function(inputValue) {}`
|
352 | onInputKeyDown | func | undefined | input keyDown handler; call `event.preventDefault()` to override default `Select` behavior: `function(event) {}`
|
353 | onOpen | func | undefined | handler for when the menu opens: `function () {}`
|
354 | onValueClick | func | undefined | onClick handler for value labels: `function (value, event) {}`
|
355 | openOnFocus | bool | false | open the options menu when the input gets focus (requires searchable = true)
|
356 | optionRenderer | func | undefined | function which returns a custom way to render the options in the menu
|
357 | options | array | undefined | array of options
|
358 | placeholder | string\|node | 'Select ...' | field placeholder, displayed when there's no value
|
359 | scrollMenuIntoView | bool | true | whether the viewport will shift to display the entire menu when engaged
|
360 | searchable | bool | true | whether to enable searching feature or not
|
361 | searchingText | string | 'Searching...' | message to display whilst options are loading via asyncOptions, or when `isLoading` is true
|
362 | searchPromptText | string\|node | 'Type to search' | label to prompt for search input
|
363 | tabSelectsValue | bool | true | whether to select the currently focused value when the `[tab]` key is pressed
|
364 | value | any | undefined | initial field value
|
365 | valueKey | string | 'value' | the option property to use for the value
|
366 | valueRenderer | func | undefined | function which returns a custom way to render the value selected `function (option) {}`
|
367 |
|
368 | ### Methods
|
369 |
|
370 | Right now there's simply a `focus()` method that gives the control focus. All other methods on `<Select>` elements should be considered private and prone to change.
|
371 |
|
372 | ```javascript
|
373 | // focuses the input element
|
374 | <instance>.focus();
|
375 | ```
|
376 |
|
377 | # Contributing
|
378 |
|
379 | See our [CONTRIBUTING.md](https://github.com/JedWatson/react-select/blob/master/CONTRIBUTING.md) for information on how to contribute.
|
380 |
|
381 | Thanks to the projects this was inspired by: [Selectize](http://brianreavis.github.io/selectize.js/) (in terms of behaviour and user experience), [React-Autocomplete](https://github.com/rackt/react-autocomplete) (as a quality React Combobox implementation), as well as other select controls including [Chosen](http://harvesthq.github.io/chosen/) and [Select2](http://ivaynberg.github.io/select2/).
|
382 |
|
383 |
|
384 | # License
|
385 |
|
386 | MIT Licensed. Copyright (c) Jed Watson 2016.
|