Giter Site home page Giter Site logo

hubspot / react-select-plus Goto Github PK

View Code? Open in Web Editor NEW
283.0 142.0 94.0 12.25 MB

Fork of https://github.com/JedWatson/react-select with option group support

Home Page: http://github.hubspot.com/react-select-plus/

License: MIT License

CSS 8.01% JavaScript 91.99%
react hubspot

react-select-plus's Introduction

React-Select-Plus

A fork of JedWatson/React-Select with support for option groups.

🚨 Project status 🚨

This fork is no longer actively maintained. The primary purpose of this project was to add option group support to react-select, a feature that will be supported in the upcoming react-select 2.0. Another alternative worth checking out is downshift, which provides low-level building blocks for building custom dropdown components.

Demo & Examples

Live demo: github.hubspot.com/react-select-plus/

Installation

The easiest way to use react-select is to install it from npm and build it into your app with Webpack.

yarn add react-select-plus

You can then import react-select-plus and its styles in your application as follows:

import Select from 'react-select-plus';
import 'react-select-plus/dist/react-select-plus.css';

You can also use the standalone UMD build by including dist/react-select-plus.js and dist/react-select-plus.css in your page. If you do this you'll also need to include the dependencies. For example:

<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
<script src="https://unpkg.com/[email protected]/index.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-input-autosize.js"></script>
<script src="https://unpkg.com/react-select-plus/dist/react-select-plus.js"></script>

<link rel="stylesheet" href="https://unpkg.com/react-select-plus/dist/react-select-plus.css">

Usage

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.

Options should be provided as an Array of Objects, 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.

The value property of each option should be either a string or a number.

When the value is changed, onChange(selectedValueOrValues) will fire. Note that (as of 1.0) you must handle the change and pass the updated value to the Select.

import React from 'react';
import Select from 'react-select-plus';

class App extends React.Component {
  state = {
    selectedOption: '',
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
  	const { selectedOption } = this.state;
  	const value = selectedOption && selectedOption.value;
  	
    return (
      <Select
        name="form-field-name"
        value={value}
        onChange={this.handleChange}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
}

You can customise the valueKey and labelKey props to use a different option shape.

Option Groups

You can generate option groups by structuring your options in a nested way as follows:

const options = [
	{
		label: 'Primary Colors', options: [
			{ label: 'Yellow', value: 'yellow' },
			{ label: 'Red', value: 'red' },
			{ label: 'Blue', value: 'blue' }
		]
	},
	{
		label: 'Secondary Colors', options: [
			{ label: 'Orange', value: 'orange' },
			{
				label: 'Purple', options: [
					{ label: 'Light Purple', value: 'light_purple' },
					{ label: 'Medium Purple', value: 'medium_purple' },
					{ label: 'Dark Purple', value: 'dark_purple' }
				]
			},
			{ label: 'Green', value: 'green' }
		]
	},
	{
		label: 'White',
		value: 'white',
	}
];

Custom classNames

You can provide a custom className prop to the <Select> component, which will be added to the base .Select className for the outer container.

The built-in Options renderer also support custom classNames, just add a className property to objects in the options array.

Multiselect options

You can enable multi-value selection by setting multi={true}. In this mode:

  • Selected options will be removed from the dropdown menu by default. If you want them to remain in the list, set removeSelected={false}
  • The selected values are submitted in multiple <input type="hidden"> fields, use the joinValues prop to submit joined values in a single field instead
  • The values of the selected items are joined using the delimiter prop to create the input value when joinValues is true
  • A simple value, if provided, will be split using the delimiter prop
  • The onChange event provides an array of selected options or a comma-separated string of values (eg "1,2,3") if simpleValue is true
  • By default, only options in the options array can be selected. Use the Creatable Component (which wraps Select) to allow new options to be created if they do not already exist. Hitting comma (','), ENTER or TAB will add a new option. Versions 0.9.x and below provided a boolean attribute on the Select Component (allowCreate) to achieve the same functionality. It is no longer available starting with version 1.0.0.
  • By default, selected options can be cleared. To disable the possibility of clearing a particular option, add clearableValue: false to that option:
var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two', clearableValue: false }
];

Note: the clearable prop of the Select component should also be set to false to prevent allowing clearing all fields at once

Accessibility Note

Selected values aren't focus targets, which means keyboard users can't tab to them, and are restricted to removing them using backspace in order. This isn't ideal and I'm looking at other options for the future; in the meantime if you want to use a custom valueComponent that implements tabIndex and keyboard event handling, see #2098 for an example.

Async options

If you want to load options asynchronously, use the Async export and provide a loadOptions Function.

The function takes two arguments String input, Function callbackand will be called when the input text is changed.

When your async process finishes getting the options, pass them to callback(err, data) in a Object { options: [] }.

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).

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.

import { Async } from 'react-select-plus';

const getOptions = (input, callback) => {
  setTimeout(() => {
    callback(null, {
      options: [
        { value: 'one', label: 'One' },
        { value: 'two', label: 'Two' }
      ],
      // CAREFUL! Only set this to true when there are no more options,
      // or more specific queries will not be sent to the server.
      complete: true
    });
  }, 500);
};

<Async
    name="form-field-name"
    loadOptions={getOptions}
/>

Note about filtering async options

The Async component doesn't change the default behaviour for filtering the options based on user input, but if you're already filtering the options server-side you may want to customise or disable this feature (see filtering options below)

Async options with Promises

loadOptions supports Promises, which can be used in very much the same way as callbacks.

Everything that applies to loadOptions with callbacks still applies to the Promises approach (e.g. caching, autoload, ...)

An example using the fetch API and ES6 syntax, with an API that returns an object like:

import { Async } from 'react-select-plus';

/*
 * assuming the API returns something like this:
 *   const json = [
 *      { value: 'one', label: 'One' },
 *      { value: 'two', label: 'Two' }
 *   ]
 */

const getOptions = (input) => {
  return fetch(`/users/${input}.json`)
    .then((response) => {
      return response.json();
    }).then((json) => {
      return { options: json };
    });
}

<Async
  name="form-field-name"
  value="one"
  loadOptions={getOptions}
/>

Async options loaded externally

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.

import Select from 'react-select-plus';

let isLoadingExternally = true;

<Select
  name="form-field-name"
  isLoading={isLoadingExternally}
  ...
/>

User-created tags

The Creatable component enables users to create new tags within react-select. 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). The easiest way to use it is like so:

import { Creatable } from 'react-select-plus';

function render (selectProps) {
  return <Creatable {...selectProps} />;
};

Combining Async and Creatable

Use the AsyncCreatable HOC if you want both async and creatable functionality. It ties Async and Creatable components together and supports a union of their properties (listed above). Use it as follows:

import { AsyncCreatable } from 'react-select-plus';

function render (props) {
  // props can be a mix of Async, Creatable, and Select properties
  return (
    <AsyncCreatable {...props} />
  );
}

Filtering options

You can control how options are filtered with the following props:

  • matchPos: "start" or "any": whether to match the text entered at the start or any position in the option value
  • matchProp: "label", "value" or "any": whether to match the value, label or both values of each option when filtering
  • ignoreCase: Boolean: whether to ignore case or match the text exactly when filtering
  • ignoreAccents: Boolean: whether to ignore accents on characters like ø or å

matchProp and matchPos both default to "any". ignoreCase defaults to true. ignoreAccents defaults to true.

Advanced filters

You can also completely replace the method used to filter either a single option, or the entire options array (allowing custom sort mechanisms, etc.)

  • filterOption: function(Object option, String filter) returns Boolean. Will override matchPos, matchProp, ignoreCase and ignoreAccents options.
  • filterOptions: function(Array options, String filter, Array currentValues) returns Array filteredOptions. Will override filterOption, matchPos, matchProp, ignoreCase and ignoreAccents options.

For multi-select inputs, when providing a custom filterOptions method, remember to exclude current values from the returned array of options.

Filtering large lists

The default filterOptions method scans the options array for matches each time the filter text changes. This works well but can get slow as the options array grows to several hundred objects. For larger options lists a custom filter function like react-select-fast-filter-options will produce better results.

Efficiently rendering large lists with windowing

The menuRenderer property can be used to override the default drop-down list of options. This should be done when the list is large (hundreds or thousands of items) for faster rendering. Windowing libraries like react-virtualized can then be used to more efficiently render the drop-down menu like so. The easiest way to do this is with the react-virtualized-select HOC. This component decorates a Select and uses the react-virtualized VirtualScroll component to render options. Demo and documentation for this component are available here.

You can also specify your own custom renderer. The custom menuRenderer property accepts the following named parameters:

Parameter Type Description
focusedOption Object The currently focused option; should be visible in the menu by default.
focusOption Function Callback to focus a new option; receives the option as a parameter.
labelKey String Option labels are accessible with this string key.
optionClassName String The className that gets used for options
optionComponent ReactClass The react component that gets used for rendering an option
optionRenderer Function The function that gets used to render the content of an option
options Array<Object> Ordered array of options to render.
selectValue Function Callback to select a new option; receives the option as a parameter.
valueArray Array<Object> Array of currently selected options.

Updating input values with onInputChange

You can manipulate the input by providing a onInputChange callback that returns a new value. Please note: When you want to use onInputChange only to listen to the input updates, you still have to return the unchanged value!

function cleanInput(inputValue) {
    // Strip all non-number characters from the input
    return inputValue.replace(/[^0-9]/g, "");
}

<Select
    name="form-field-name"
    onInputChange={cleanInput}
/>

Overriding default key-down behaviour with onInputKeyDown

Select listens to keyDown events to select items, navigate drop-down list via arrow keys, etc. You can extend or override this behaviour by providing a onInputKeyDown callback.

function onInputKeyDown(event) {
    switch (event.keyCode) {
        case 9:   // TAB
            // Extend default TAB behaviour by doing something here
            break;
        case 13: // ENTER
            // Override default ENTER behaviour by doing stuff here and then preventing default
            event.preventDefault();
            break;
    }
}

<Select
    {...otherProps}
    onInputKeyDown={onInputKeyDown}
/>

Select Props

Property Type Default Description
aria-describedby string undefined HTML ID(s) of element(s) that should be used to describe this input (for assistive tech)
aria-label string undefined Aria label (for assistive tech)
aria-labelledby string undefined HTML ID of an element that should be used as the label (for assistive tech)
arrowRenderer function undefined Renders a custom drop-down arrow to be shown in the right-hand side of the select: arrowRenderer({ onMouseDown, isOpen }). Won't render when set to null
autoBlur boolean false Blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices
autofocus boolean undefined deprecated; use the autoFocus prop instead
autoFocus boolean undefined autofocus the component on mount
autoload boolean true whether to auto-load the default async options set
autosize boolean true If enabled, the input will expand as the length of its value increases
backspaceRemoves boolean true whether pressing backspace removes the last item when there is no input value
backspaceToRemoveMessage string 'Press backspace to remove {last label}' prompt shown in input when at least one option in a multiselect is shown, set to '' to clear
className string undefined className for the outer element
clearable boolean true should it be possible to reset value
clearAllText string 'Clear all' title for the "clear" control when multi is true
clearRenderer function undefined Renders a custom clear to be shown in the right-hand side of the select when clearable true: clearRenderer()
clearValueText string 'Clear value' title for the "clear" control
closeOnSelect boolean true whether to close the menu when a value is selected
deleteRemoves boolean true whether pressing delete key removes the last item when there is no input value
delimiter string ',' delimiter to use to join multiple values
disabled boolean false whether the Select is disabled or not
escapeClearsValue boolean true whether escape clears the value when the menu is closed
filterOption function undefined method to filter a single option (option, filterString) => boolean
filterOptions boolean or function undefined boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) => [options]
id string undefined html id to set on the input element for accessibility or tests
ignoreAccents boolean true whether to strip accents when filtering
ignoreCase boolean true whether to perform case-insensitive filtering
inputProps object undefined custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
inputRenderer function undefined renders a custom input component
instanceId string increment instance ID used internally to set html ids on elements for accessibility, specify for universal rendering
isLoading boolean false whether the Select is loading externally or not (such as options being loaded)
joinValues boolean false join multiple values into a single hidden input using the delimiter
labelKey string 'label' the option property to use for the label
matchPos string 'any' (any, start) match the start or entire string when filtering
matchProp string 'any' (any, label, value) which option property to filter on
menuBuffer number 0 buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
menuContainerStyle object undefined optional style to apply to the menu container
menuRenderer function undefined Renders a custom menu with options; accepts the following named parameters: menuRenderer({ focusedOption, focusOption, options, selectValue, valueArray })
menuStyle object undefined optional style to apply to the menu
multi boolean undefined multi-value input
name string undefined field name, for hidden <input /> tag
noResultsText string 'No results found' placeholder displayed when there are no matching search results or a falsy value to hide it (can also be a react component)
onBlur function undefined onBlur handler: function(event) {}
onBlurResetsInput boolean true Whether to clear input on blur or not. If set to false, it only works if onCloseResetsInput is false as well.
onChange function undefined onChange handler: function(newOption) {}
onClose function undefined handler for when the menu closes: function () {}
onCloseResetsInput boolean true whether to clear input when closing the menu through the arrow
onFocus function undefined onFocus handler: function(event) {}
onInputChange function undefined onInputChange handler/interceptor: function(inputValue: string): string
onInputKeyDown function undefined input keyDown handler; call event.preventDefault() to override default Select behaviour: function(event) {}
onMenuScrollToBottom function undefined called when the menu is scrolled to the bottom
onOpen function undefined handler for when the menu opens: function () {}
onSelectResetsInput boolean true whether the input value should be reset when options are selected. Also input value will be set to empty if 'onSelectResetsInput=true' and Select will get new value that not equal previous value.
onValueClick function undefined onClick handler for value labels: function (value, event) {}
openOnClick boolean true open the options menu when the control is clicked (requires searchable = true)
openOnFocus boolean false open the options menu when the control gets focus
optionClassName: string undefined additional class(es) to apply to the elements
optionComponent function undefined option component to render in dropdown
optionRenderer function undefined custom function to render the options in the menu
options array undefined array of options
removeSelected boolean true whether the selected option is removed from the dropdown on multi selects
pageSize number 5 number of options to jump when using page up/down keys
placeholder string or node 'Select ...' field placeholder, displayed when there's no value
required boolean false applies HTML5 required attribute when needed
resetValue any null value to set when the control is cleared
rtl boolean false use react-select in right-to-left direction
scrollMenuIntoView boolean true whether the viewport will shift to display the entire menu when engaged
searchable boolean true whether to enable searching feature or not
searchPromptText string or node 'Type to search' label to prompt for search input
simpleValue boolean false pass the value to onChange as a string
style object undefined optional styles to apply to the control
tabIndex string or number undefined tabIndex of the control
tabSelectsValue boolean true whether to select the currently focused value when the [tab] key is pressed
trimFilter boolean false whether to trim whitespace from the filter value
value any undefined initial field value
valueComponent function function which returns a custom way to render/manage the value selected <CustomValue />
valueKey string 'value' the option property to use for the value
valueRenderer function undefined function which returns a custom way to render the value selected function (option) {}
wrapperStyle object undefined optional styles to apply to the component wrapper

Async Props

Property Type Default Description
autoload boolean true automatically call the loadOptions prop on-mount
cache object undefined Sets the cache object used for options. Set to false if you would like to disable caching.
loadingPlaceholder string or node 'Loading...' label to prompt for loading search result
loadOptions function undefined function that returns a promise or calls a callback with the options: function(input, [callback])

Creatable properties

Property Type Description
children function Child function responsible for creating the inner Select component. This component can be used to compose HOCs (eg Creatable and Async). Expected signature: (props: Object): PropTypes.element
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
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
newOptionCreator function Factory to create new option. Expected signature: ({ label: string, labelKey: string, valueKey: string }): Object
onNewOptionClick function new option click handler, it calls when new option has been selected. function(option) {}
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 default. Expected signature: ({ keyCode: number }): boolean
promptTextCreator function Factory for overriding default option creator prompt label. By default it will read 'Create option "{label}"'. Expected signature: (label: String): String

Methods

Use the focus() method to give the control focus. All other methods on <Select> elements should be considered private.

// focuses the input element
<instance>.focus();

Contributing

See our CONTRIBUTING.md for information on how to contribute.

Thanks to the projects this was inspired by: Selectize (in terms of behaviour and user experience), React-Autocomplete (as a quality React Combobox implementation), as well as other select controls including Chosen and Select2.

License

MIT Licensed. Copyright (c) HubSpot 2017.

react-select-plus's People

Contributors

agirton avatar aronstrandberg avatar banderson avatar brianreavis avatar bruderstein avatar bvaughn avatar chopinsky avatar craigdallimore avatar danielheath avatar davidroeca avatar dcousens avatar dekelb avatar dmatteo avatar fhelwanger avatar frankievx avatar gojohnnygo avatar gwyneplaine avatar jedwatson avatar jgautsch avatar jochenberger avatar jooj123 avatar jossmac avatar julen avatar karaggeorge avatar khankuan avatar mrleebo avatar nomadrat avatar rockallite avatar trevorburnham avatar yuri-sakharov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-select-plus's Issues

Include `name` property in `onChange(selected)`

This would make it easier to use a single onChange handler for tracking current state.

e.g. The same change handler

const onChange = (selected) => {
  this.setState({ [selected.name]: selected.value })
}

Could be used for

<Select
    name="form-field-name-one"
    value="one"
    options={optionsForOne}
    onChange={onChange}
  />

<Select
    name="form-field-name-two"
    value="two"
    options={optionsForTwo}
    onChange={onChange}
  />

Option to hide option group label

So that if I have a list like below, I can hide "Fruits" and have the "All fruits" option act as the label for that group.

All fruits
Fruits <-- option to hide this
    Apples
    Oranges
    Mangos

Another solution would be to make the option group label selectable.

How can i choose the group title as a value?

It would be awesome if somebody told me is this functionality possible or not.
I want the group parent was be able to be chosen.
So, if we had something like that:

Fruits
--apples
--pineapples
--mangos
Vegetables
--tomatos
--potato

we would choose "Fruits" and "Vegetables" as a finish results.
Thx you

Create value to become first item- `showNewOptionAtTop` prop

Hi,

Great work on this.

I would like to make it so "Create" is not the first/auto highlighted option when a user starts typing.

According the the main (non-plus of react-select) it was put in this commit (here). How can I integrate this feature myself?

I created a screenshot to help explain.

screen shot 2017-05-14 at 9 34 54 pm

react-select leaving out a particular option

I'm having this weird bug, I don't know if I'm doing something wrong. It seems like something related to asynchronous data loading, but I don't know how to debug this.

I'm using react-select-plus 1.0.0-beta14 with google place autocomplete API, but I can't get a particular location to show immediately (and I really need that location to display). I'm loading the data asynchronously using "loadOptions" and promises. Google place autocomplete API always returns 5 locations, but for some reason, for a particular input, react-select displays only 4 even though if I write out options in the loadOptions promise, all 5 are there. Also, if, after only those 4 values are displayed, I click somewhere else so that the react-select loses focus and dropdown options are hidden, when I click on the react-select's input field again so that the dropdown values display again, all 5 are there as they should be. Keep in mind that it's always leaving out the same option. I haven't noticed it with any other location. Here's my code:

loadAutocomplete(input){
        let fetchUrl = baseUrl + "api/services/google/autocomplete?input=" + input;
        fetchUrl = encodeURI(fetchUrl);
        return fetch(fetchUrl, {method:"get", headers:{"Content-Type":"application/json"}})
            .then( response => response.json())
            .then(suggestions => {
                console.log(suggestions);   //WRITES OUT CORRECT LOCATIONS (ALL 5)
                return ({options:suggestions});
            })
    }

Options I console.log() before returning the from promise (the second one is the one that gets left out):

[
  {
    "label": "Hostal Sol Madrid, Calle Marqués Viudo de Pontejos, Madrid, Spain",
    "value": "ChIJbz9ISX4oQg0Rq2taBHu-DBA"
  },
  {
    "label": "Sol, Madrid, Spain",
    "value": "ChIJf-YYGX4oQg0RRvnJ0KBzhDM"
  },
  {
    "label": "Sol Pelícanos Ocas, Calle Gerona, Benidorm, Spain",
    "value": "ChIJo73enFcEYg0RvN7lZs3Ygik"
  },
  {
    "label": "Sol Duc Hot Springs Resort, Port Angeles, WA, United States",
    "value": "ChIJq6YwIPBEjlQRVeg28xhFwrU"
  },
  {
    "label": "Sol Principe, Torremolinos, Spain",
    "value": "ChIJDdCCJOj7cg0RjqFJincQ65E"
  }
]

On input screenshot
lose focus and then refocus again screenshot

Support themes

Project has a lot of styles, which look a little messy. Would you like to use cssnext and theming instead? I can help with migrating.

possible to select opt-group with value?

from your example you have opt-groups with a label and one with both a label and value is there some way im missing to add the ability to select an opt-group if it contains a value?

Options created with option group not clickable in mobile

Im a building phonegap app with react where I am using this excellent library. The problem I face is although the options click works for options rendered without opt group on mobile it does not work for options rendered with opt group on mobile. Seems to work on desktop for both. I tried adding the following code

this.props.onSelect(this.props.option, event); on handleMouseDown function but this does not solve the issue.

It is already not working

ERROR in ./node_modules/react-input-autosize/lib/AutosizeInput.js
Module not found: Error: Can't resolve 'create-react-class' in '/home/.../node_modules/react-input-autosize/lib'
@ ./node_modules/react-input-autosize/lib/AutosizeInput.js 7:18-47
@ ./node_modules/react-select-plus/lib/Select.js
...

why did you change onInputChange?

react-select
function(inputValue: string): string

react-select-plus
function(inputValue) {}

I'm trying to add feature that will automatically split user pasted string of values separated by comma, into react-select values, but after that I need to remove initial user input.
It doesn't work because onInputChange is ignoring the value returned from it.

EDIT:
ok, I see in the source code that implementation is the same for both :/

Demopage cities-dropdown does not work on scroll.

When I open the http://github.hubspot.com/react-select-plus/ demo page and try to use the cities dropdown, scrolling the dropdown, cities start disappearing and soon I'm scrolling a white dropdown. (Chrome Version 60.0.3112.113 (Official Build) (64-bit), OSX 10.12.6)

image

Our dataset is 10k+ rows, and we most likely need the react-virtualized-select functionality. Without it, react-select-plus was too slow. From the current examples I do not quite understand how to get option groups and virtualized-select both working at the same time. The virtualized demo does not seem to contain groups and also it does not seem to work. :(

ignoreCase results in bad user experience

When using the (default enabled) ignoreCase option, the user input is converted to lowercase in the input box. I'ld prefer to leave the input as entered by the user, while converting it to lowercase when performing the search. In the current situation my users are surprised by the fact that their input is modified (checking if their caps lock key is activated...)

Hover functionality is not working on using optionRenderer

Hi,
In my function (optionRenderer) when I return some other text instead of option.label, option:hover property (background color change) does not work.

optionRenderer(option) {
let label = option.label
let split = label.split("***")
if(split.length > 1) {
return (
{split[0]+" "}in{" "}{split[1]}
);
}
return ({option.label});
}

So in above case for options which have text option.label, hover is working.
While for the one which is using split, hover is not working.

React-select-plus "isLoading={true}" property is not showing the loader

Hello everyone, i'm using react-select-plus and i use onInputChange for calling a service and fetching the options. I've read carefully the documentation and is saying that if we desire to load async options externally we should use the "isLoading" property. But when i've set it in my Select Tag it does not work.
Here is my code:
<Select
id="portf"
options={opts}
isLoading={true}
value={portfolioValue}
onChange={value => portfolioSelector(value, mobileNavCollapsed)}
onInputChange={value =>
searchPortfolioHandler(value)}
/>
Do you have any idea of how to handle this? This is causing me a severe problem because even i have values in my state my list is not refreshing.

Cannot

Hi,

Im trying to make an Select component that integrate with React-Formsy.

in order to do so - I want to pass the <input ../> component an required=true property (supported via select's inputProps).

<Select
    name="form-field-name"
    value="one"
    options={options}
    onChange={logChange}
     inputProps={{
              required: true,
              otherField: true
      }}

  />

var options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

function logChange(val) {
    console.log("Selected: " + val);
}

When I inspect the components in react chrome debugger - I can see that otherField: true but required: false.

As a matter of fact - all other props are propagated well to <input> except required.

Any Suggestions?

Thanks.

Callback for onSelect?

Would you be open to a PR exposing an onSelect(option) callback for Option? I would like to be able to access the option data immediately when the user select it from the dropdown.

Double click for expanding

Thanks for using react-select!

If you are reporting an error please include a test case that demonstrates the issue you're reporting!
This is very helpful to maintainers in order to help us see the issue you're seeing.

Here is a Plunker you can fork that has react-select loaded and supports JSX syntax:
https://plnkr.co/edit/HTmtER9AMNcPoWhXV707?p=preview

You may also find the online Babel tool quite helpful if you wish to use ES6/ES7 syntax not yet supported by the browser you are using.

Tether support?

Is there a way to use this library with tether?

Are there any examples of this ?

If first item in menu is an option group then it is cut off when the menu opens

'.Select-menu. scrollTop is set to the offset of the "first" item - option group label is not considered as the first/focused item therefore '.Select-menu' is scrolled past the option group label meaning the user has to scroll back up to see the option group label.

Can be recreated with the docs option group example by removing "Black" option and having "Primary Colors" as the first option.

How do we use option groups?

This is just a documentation issue.

I've been experimenting with react-select-plus, and it looks like it does exactly what I need. However, it's unclear to me how to use the "option groups" feature. You have an example of option groups on your Demos page, but I cannot find anything in your documentation/README on how to use it.

Not an urgent issue, just would like to understand how to take advantage of that feature.
Thanks!

Add option to show new creatable item as first or last option

Hello,
I'm not sure what your general policy is for making changes to react-select-plus that are not already merged upstream into react-select but I thought I'd try anyway! 😎

Sometimes I'd like to discourage my users from creating a new option without at least looking through the list for similar options. In this case, I'd like the new "creatable" option to be last, rather than first.

I created a PR in react-select (JedWatson/react-select#1436) for this but I'm also using react-select-plus and it would be very useful for me to have it here.

The key change is adding a boolean prop to Creatable and use either unshift as it's currently doing or use push based on the prop here.

if (showNewOptionAtTop) {
  filteredOptions.unshift(this._createPlaceholderOption);
} else {
  filteredOptions.push(this._createPlaceholderOption);
}

Please let me know what you think. I'd be happy to fork and create a PR but I don't want to duplicate my changes here if you'd rather wait for them to merge it upstream.

Thanks!

Every backspace Removes call load option method.

How to call every backspace remove call load option. I am using select.Async control in every input change method call fetch method and fetch data but when I press backspace then first time called that load option method but in next time that can't call load option method.

` <Select.Async
onChange={this.onChange}
valueKey="placeID"
filterOptions={this.filterOptions}
labelKey="cityState"
loadOptions={this.getUsers}
onInputChange={inp => this.onInputChange(inp)}
onBlur={this.onBlur}
onInputKeyDown={inp => this.onInputKeyDown(inp)}
onFocus={this.onFocousSearch}
value={this.state.value}
searchPromptText="Please enter 3 or more characters"
loadingPlaceholder={this.state.loadingtext}
noResultsText="No results found"
options={this.state.options}
placeholder={this.state.placeholdervalue}
autoBlur

/> `

In above code in load option that get user method call. My get User method is :
`
getUsers = (input) => {
console.log(input);
if (!input) {
return Promise.resolve({ options: [] });
}
if (input.length > 2) {
const newstate = this.state;
newstate.loadingtext = 'Searching...';
this.setState({ newstate });
const searchLocation = Object.assign({}, cookie.load('cLocation'));
searchLocation.searchText = input;
searchLocation.isBusiness = false;
console.log(input.toString().length);
return fetch(sourceName.searchNavbar, apiUrl.locationAndBusiness,
searchLocation)
.then(json => ({ options: json.data }));
}
return null;
}

`

When I click first time back space then get user method call but in second time I pressed back space then not called that get user method. How to call every backspace remove call this method.

Deprecation warning about PropTypes

Here's the messages:

Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

AsyncCreatableSelect: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

Select Multiple height when initially loaded vs. populated

I have an interface that loads preselected options inside a multi-select box. When react is loading the element, the height seems to be determined on an empty select box, which then renders other elements on top or below the select box. When I do anything to either element, react re-renders them, and then they look fine. Any ideas?

This is wrong...
screen shot 2016-12-29 at 8 11 01 am

This is right!
screen shot 2016-12-29 at 8 11 17 am

Selects which are not searchable can't be associated with htmlFor

If the has searchable={false} set, then using htmlFor for associating labels with the input doesn't work. See plunk: https://plnkr.co/edit/cr6cMK966vaHlUVwsNAZ?p=preview (for some reason, github's markdown parser is not working - the markdown is being parsed erratically, so links are not working. Please copy-paste the plunk url)

Dropdowns Need To Be Clicked Twice: Patch3

When using version 1.0.0-rc.3.patch3, it seems the Select fields now require 2 clicks to activate the dropdown showing the options. The first one focuses on the field, the second click actually opens the dropdown. This can even be seen on the examples page: http://github.hubspot.com/react-select-plus/. All those examples (except for the Cities (Large Dataset) example) require 2 clicks for the dropdown to appear.

Please let me know if this is intended or a bug. Thanks!

[1.0.0-beta13] Async options with Promises displays [object Promise] as input value

Hey,
I am having an issue with 1.0.0-beta13 version, as with Async options whenever user tries to write something in the input, it changes typed value to [object Promise]. There is already a fix for that at react-select - is there any chance to merge this fix to react-select-plus and publish a new version to npm?

Issue on react-select:
JedWatson/react-select#940

Pull Request fixing that issue:
JedWatson/react-select#941

Thanks!

Collapse is not showing value when i'm giving inpu

Hello everyone, i'm using react-select-plus and redux saga for calling a service. My code is here:
<Select
id="portf"
options={opts}
value={portfolioValue}
onChange={value => portfolioSelector(value, mobileNavCollapsed)}
placeholder="Select Portfolio"
onInputKeyDown={event => searchPortfolioHandler(event.target.value)}
/>
When the user enters something from his keyboard the service is called successfully and my state is updating correctly. The only issue i'm facing is that when i'm giving inputs my list is not updating instantly. My list is updating when i click out of my dropdown and then click again. Here is an animated GIF for my issue.
webp net-gifmaker 1

Request?

Thanks for using react-select!

It has become fairly common practice from what I can tell for users of CSSModules to parse .global.css and have that indicate that css modules should not be used. It would be awesome if that were the case here so that it would be much simpler to implement the css with a simple import.

I would think its a fairly easy thing to support and would be an appreciated feature.

Thanks a ton to everyone who maintains this. I used the old select a ton and love what I am seeing here -- starting the path to upgrade now.

{
        test: /\.global\.css$/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              sourceMap: true,
            },
          },
        ],
      },
      {
        test: /^((?!\.global).)*\.css$/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              sourceMap: true,
              camelCase: true,
              importLoaders: 1,
              localIdentName: '[name]__[local]__[hash:base64:5]',
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              sourceMap: true,
            },
          },
        ],
      },

future?

Is the plan to keep this project separate and distinct from react-select, or is it eventually going to get merged back.

react-select-plus + search not working with comma

I am using react-select-plus control in react for drop down. When I search any data using space that's work fine.
Now, My Issue is In data there are specific comma in that word then Isn't work.
example in search list contain comma for example ( ann, archive ) now I try to search using ( ann archive )
then ( ann, archive ) not display in result set. I need to display that result. I want ignore that comma when searching result. so that ignore comma in my search criteria and give me that data.

How, should I solve this.

Please help me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.