npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-select-plus-with-marked

v1.0.0-beta13

Published

A Select control built with and for ReactJS

Downloads

3

Readme

React-Select-Plus

A Select control for React based on JedWatson/React-Select.

New version 1.0.0-beta

I've nearly completed a major rewrite of this component (see issue #568 for details and progress). The new code has been merged into master, and [email protected] has been published to npm and bower.

1.0.0 has some breaking changes. The documentation below still needs to be updated for the new API; notes on the changes can be found in CHANGES.md and will be finalised into HISTORY.md soon.

Our tests need some major updates to work with the new API (see #571) and are causing the build to fail, but the component is stable and robust in actual usage.

Testing, feedback and PRs for the new version are appreciated.

Demo & Examples

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

To build the new 1.0.0 examples locally, clone this repo then run:

npm install
npm start

Then open localhost:8000 in a browser.

Installation

The easiest way to use React-Select is to install it from NPM and include it in your own React build process (using Browserify, etc).

npm install react-select-plus --save

You can also use the standalone build by including dist/react-select.js and dist/react-select.css in your page. If you use this, make sure you have already included the following dependencies:

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 set to either a string or a number.

When the value is changed, onChange(newValue, [selectedOptions]) will fire.

var Select = require('react-select-plus');

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

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

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

Multiselect options

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

  • Selected options will be removed from the dropdown menu
  • The selected values are submitted in multiple <input type="hidden"> fields, use joinValues 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 the selected options as the second argument
  • The first argument to onChange is always a string, regardless of whether the values of the selected options are numbers or strings
  • 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.
  • 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

Async options

If you want to load options asynchronously, instead of providing an options Array, 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.

var Select = require('react-select-plus');

var getOptions = function(input, callback) {
	setTimeout(function() {
		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);
};

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

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 Select 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 };
    });
}

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

var Select = require('react-select-plus');

var isLoadingExternally = true;

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

Filtering options

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

  • 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

matchProp and matchPos both default to "any". ignoreCase 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 and ignoreCase options.
  • filterOptions: function(Array options, String filter, Array currentValues) returns Array filteredOptions. Will override filterOption, matchPos, matchProp and ignoreCase options.

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

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

Windowing libraries like react-virtualized can then be used to more efficiently render the drop-down menu like so:

menuRenderer({ focusedOption, focusOption, labelKey, options, selectValue, valueArray }) {
  const focusedOptionIndex = options.indexOf(focusedOption);
  const option = options[index];
  const isFocusedOption = option === focusedOption;

  return (
    <VirtualScroll
      ref="VirtualScroll"
      height={200}
      rowHeight={35}
      rowRenderer={(index) => (
        <div
          onMouseOver={() => focusOption(option)}
          onClick={() => selectValue(option)}
        >
          {option[labelKey]}
        </div>
      )}
      rowsCount={options.length}
      scrollToIndex={focusedOptionIndex}
      width={200}
    />
  )
}

Check out the demo site for a more complete example of this.

Updating input values with onInputChange

You can manipulate the input using the onInputChange and returning a new 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}
/>

Further options

Property	|	Type		|	Default		|	Description

:-----------------------|:--------------|:--------------|:-------------------------------- addLabelText | string | 'Add "{label}"?' | text to display when allowCreate is true allowCreate | bool | false | allow new options to be created in multi mode (displays an "Add <option> ?" item when a value not already in the options array is entered) autoBlur | bool | false | Blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices autoload | bool | true | whether to auto-load the default async options set autosize | bool | true | If enabled, the input will expand as the length of its value increases backspaceRemoves | bool | true | whether pressing backspace removes the last item when there is no input value cache | bool | true | enables the options cache for asyncOptions (default: true) className | string | undefined | className for the outer element clearable | bool | true | should it be possible to reset value clearAllText | string | 'Clear all' | title for the "clear" control when multi is true clearValueText | string | 'Clear value' | title for the "clear" control resetValue | any | null | value to use when you clear the control delimiter | string | ',' | delimiter to use to join multiple values disabled | bool | false | whether the Select is disabled or not filterOption | func | undefined | method to filter a single option: function(option, filterString) filterOptions | func | undefined | method to filter the options array: function([options], filterString, [values]) ignoreCase | bool | true | whether to perform case-insensitive filtering inputProps | object | {} | custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} isLoading | bool | false | whether the Select is loading externally or not (such as options being loaded) joinValues | bool | false | join multiple values into a single hidden input using the delimiter labelKey | string | 'label' | the option property to use for the label loadOptions | func | undefined | function that returns a promise or calls a callback with the options: function(input, [callback]) 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 menuRenderer | func | undefined | Renders a custom menu with options; accepts the following named parameters: menuRenderer({ focusedOption, focusOption, options, selectValue, valueArray }) multi | bool | undefined | multi-value input name | string | undefined | field name, for hidden <input /> tag newOptionCreator | func | undefined | factory to create new options when allowCreate is true noResultsText | string | 'No results found' | placeholder displayed when there are no matching search results or a falsy value to hide it onBlur | func | undefined | onBlur handler: function(event) {} onBlurResetsInput | bool | true | whether to clear input on blur or not onChange | func | undefined | onChange handler: function(newValue) {} onClose | func | undefined | handler for when the menu closes: function () {} onFocus | func | undefined | onFocus handler: function(event) {} onInputChange | func | undefined | onInputChange handler: function(inputValue) {} onOpen | func | undefined | handler for when the menu opens: function () {} onValueClick | func | undefined | onClick handler for value labels: function (value, event) {} openOnFocus | bool | false | open the options menu when the input gets focus (requires searchable = true) optionRenderer | func | undefined | function which returns a custom way to render the options in the menu options | array | undefined | array of options placeholder | string|node | 'Select ...' | field placeholder, displayed when there's no value renderInvalidValues | bool | false | if a value does not match any options, render it anyway scrollMenuIntoView | bool | true | whether the viewport will shift to display the entire menu when engaged searchable | bool | true | whether to enable searching feature or not searchingText | string | 'Searching...' | message to display whilst options are loading via asyncOptions, or when isLoading is true searchPromptText | string | 'Type to search' | label to prompt for search input tabSelectsValue | bool | true | whether to select the currently focused value when the [tab] key is pressed value | any | undefined | initial field value valueKey | string | 'value' | the option property to use for the value valueRenderer | func | undefined | function which returns a custom way to render the value selected

Methods

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.

// 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 2016.