React top-level api

Installation

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


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

importSelectfrom'react-select';import'react-select/dist/react-select.css';

You can also use the standalone UMD build by including and in your page. If you do this you’ll also need to include the dependencies. For example:

<scriptsrc="https://unpkg.com/react@15.6.1/dist/react.js"><script><scriptsrc="https://unpkg.com/react-dom@15.6.1/dist/react-dom.js"><script><scriptsrc="https://unpkg.com/prop-types@15.5.10/prop-types.js"><script><scriptsrc="https://unpkg.com/classnames@2.2.5/index.js"><script><scriptsrc="https://unpkg.com/react-input-autosize@2.0.0/dist/react-input-autosize.js"><script><scriptsrc="https://unpkg.com/react-select@1.2.1/dist/react-select.js"><script><linkrel="stylesheet"href="https://unpkg.com/react-select@1.2.1/dist/react-select.css">

Installation

npm install react-select --save

At this point you can import react-select and its styles in your application as follows:

importSelectfrom'react-select';import'react-select/dist/react-select.css';

You can also use the standalone build by including and in your page. (If you do this though you’ll also need to include the dependencies.) For example:

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"><script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"><script><scriptsrc="https://unpkg.com/classnames/index.js"><script><scriptsrc="https://unpkg.com/react-input-autosize/dist/react-input-autosize.js"><script><scriptsrc="https://unpkg.com/react-select/dist/react-select.js"><script><linkrel="stylesheet"href="https://unpkg.com/react-select/dist/react-select.css">

Configuration

Below is all the available options you can pass to the component. Options without defaults are required.

Name Type Default Description
options array
value string, array undefined The value should be an array if multiple mode.
multiple boolean false Set to true if you want to allow multiple selected options.
search boolean false Set to true to enable search functionality
disabled boolean false Disables all functionality
placeholder string empty string Displayed if no option is selected and/or when search field is focused with empty value.
autoComplete string, on/off off Disables/Enables autoComplete functionality in search field.
autoFocus boolean false Autofocus on select
fuse object, boolean true Use fuse.js to apply fuzzy search on search. Set to true to use default options or pass a fuse.js config option. If is enabled and no callback is passed, this will be set to automatically.
className string, function select-search-box
onChange function null Function to receive and handle value changes.
printOptions string auto Can be: auto, always, never, on-focus. This property controls when the options list should be rendered.
closeOnSelect boolean true The selectbox will blur by default when selecting an option. Set this to false to prevent this behavior.
renderOption function null
renderValue function null
renderGroupHeader function null
getOptions function null

HOC

We’ve extracted some key features into separate HOCs to keep the main library as small as possible

importSelectfrom'react-select-me';importmakeVirtualizedfrom'react-select-me/lib/hoc/makeVirtualized';constVirtualizedSelect=makeVirtualized(Select);<VirtualizedSelect options={options} value={this.state.value} onChange={this.onChange}>;
importSelectfrom'react-select-me';importmakeImmutablefrom'react-select-me/lib/hoc/makeImmutable';constImmutableSelect=makeImmutable(Select);<ImmutableSelect options={options} value={this.state.value} onChange={this.onChange}>;

Installation

npm install react-select --save

At this point you can import react-select and its styles in your application as follows:

importSelectfrom'react-select';import'react-select/dist/react-select.css';

You can also use the standalone build by including and in your page. (If you do this though you’ll also need to include the dependencies.) For example:

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"><script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"><script><scriptsrc="https://unpkg.com/classnames/index.js"><script><scriptsrc="https://unpkg.com/react-input-autosize/dist/react-input-autosize.js"><script><scriptsrc="https://unpkg.com/react-select/dist/react-select.js"><script><linkrel="stylesheet"href="https://unpkg.com/react-select/dist/react-select.css">

Using FormGenerator

importReact,{Component}from'react';import{Validators,FormGenerator}from"react-reactive-form";constTextInput=({ handler, touched, hasError, meta })=>(<div><input placeholder={`Enter ${meta.label}`}{...handler()}><span>{touched&&hasError("required")&&`${meta.label} is required`}<span><div>)constCheckBox=({ handler })=>(<div><input {...handler("checkbox")}><div>)constfieldConfig={    controls{        username{            options{                validatorsValidators.required},            render TextInput,            meta{ label"Username"}},        password{            options{                validatorsValidators.required},            render TextInput,            meta{ label"Password"}},        rememberMe{            render CheckBox},        $field_0{            isStaticfalse,render({ invalid, meta{ handleReset }})=>(<div><button                      type="button"                      onClick={handleReset}>                      Reset<button><button                      type="submit"                      disabled={invalid}>                      Submit<button><div>)}},}exportdefaultclassLoginextendsComponent{handleReset=()=>{this.loginForm.reset();}handleSubmit=(e)=>{e.preventDefault();console.log("Form values",this.loginForm.value);}setForm=(form)=>{this.loginForm= form;this.loginForm.meta={            handleResetthis.handleReset}}render(){return(<form onSubmit={this.handleSubmit}><FormGenerator                    onMount={this.setForm}                    fieldConfig={fieldConfig}><form>);}}

License

The MIT License (MIT)

Copyright (c) 2017-2018 Bruno Agutoli

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Opptions

Property Type Default Description
object You can specify for each element. Possible values: , , , , , , , , , , , , ,
bool should it be possible to reset value
bool disables every events over the component
bool multi values support
bool () efficiently rendering large lists options
number () height of option menu
number () Height of each options
bool whether to enable searching feature or not
string The short hint is displayed in the input field before the user enters a value
function function that returns a promise or calls a callback with the options:
string Root element className
any If you want to specify a pre selected value
array List of values. Ex.
function It calls when open outer menu
function It calls when change selected value
function It calls when click over a option value
function It calls when click over a option value
function It calls when input is cleared
function function which returns a custom way to render the value selected function (option) {}
function function which returns a custom way to render the options in the menu (option) {}

Form wrapper component, registering fields, validations, and error handling

React Final Form 

You have to wrap your HTML form in a Form component to get access to props that React Final Form provides for you. Then, every input needs to be wrapped in the Field component, for it to be registered in the form. It also gives you access to it’s properties and state of the input like errors and information whether it’s been clicked on by a user or not. React Final Form doesn’t provide any built-in validation, so you’ll have to pass on your own. You can pass multiple validations with:

Formik

With Formik, you have to wrap your form in the Formik component which again, gives you access to various props. What’s important here, you need to set initialValues object of each field in the form for it to be registered. Using Form component is optional because all it does is automatically hooking into Formik’s handleSubmit and handleReset. Then you just use Field to create an input on the form (works the same with other inputs like radio and checkbox and for custom fields, you use component prop on the Field). Multiple validations is again as simple as passing: 

React Hook Form

As a side note to validations, both React Final Form and Formik support both Field-level, as well as Form-level validations, through passing the validate prop to their respective form wrapper component. React Hook Form supports only Field-level validation.

Custom renderers


If CSS isn’t enough, you can also control the HTML for the different parts of the component.

Callback Args Description
renderOption optionsProps: object, optionData: object, optionSnapshot: object Controls the rendering of the options.
renderGroupHeader name: string Controls the rendering of the group header name
renderValue valueProps: object, ref: React.ref, selectedValue: object Controls the rendering of the value/input element

The optionProps and the valueProps are needed for the component you render to work. For example:

<SelectSearchrenderValue={(valueProps)=><input{...valueProps}/>}/>

Monkeypatch it if you need to but make sure to not remove important props.

The optionSnapshot is an object that contains the object state: .

Installation

npm install react-select-plus --save

At this point you can import react-select and its styles in your application as follows:

importSelectfrom'react-select-plus';import'react-select-plus/dist/react-select-plus.css';

You can also use the standalone build by including and in your page. (If you do this though you’ll also need to include the dependencies.) For example:

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"><script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"><script><scriptsrc="https://unpkg.com/classnames/index.js"><script><scriptsrc="https://unpkg.com/react-input-autosize/dist/react-input-autosize.js"><script><scriptsrc="https://unpkg.com/react-select-plus/dist/react-select-plus.js"><script><linkrel="stylesheet"href="https://unpkg.com/react-select-plus/dist/react-select.css">

Variables

Before ES6 there were only one way of defining your variables: with the keyword. If you did not define them, they would be assigned to the global object. Unless you were in strict mode, then you would get an error if your variables were undefined.

Now, with ES6, there are three ways of defining your variables: , , and .

var

If you use outside of a function, it belongs to the global scope.

If you use inside of a function, it belongs to that function.

If you use inside of a block, i.e. a for loop, the variable is still available outside of that block.

has a function scope, not a block scope.

let

has a block scope.

is the block scoped version of , and is limited to the block (or expression) where it is defined.

If you use inside of a block, i.e. a for loop, the variable is only available inside of that loop.

Custom appearance with CSS Variebles

Your react file ex. MyForm.jsx

classMyFormextendsReact.Component{render(){return(){<Select className="dark-theme" options={...}>}}}

Your project CSS file ex. mysite.css

.dark-theme{--styled-select-placeholder__color#999;--styled-select__colorwhite;--styled-select__background-color#555;--styled-select__border-colorblack;--styled-select__border-width3px;--styled-select__border-radius5px;--styled-select-menu-outer__margin10px;--styled-select-menu-outer__padding;--styled-select-menu-outer__background-color#555;--styled-select-menu-outer__border-colorblack;--styled-select-menu-outer__border-stylesolid;--styled-select-menu-outer__border-width3px;--styled-select-option__background-color#444;--styled-select-option__color--focused#eee;--styled-select-option__background-color--focused#333;--styled-select-option__color--selected#eee;--styled-select-option__background-color--selected#444;}

Experimental 🔥

The following props are considered experimental because they are more prone to issues and are likely to be changed in the future. Use with caution.

In case you need to implement more complex masking behavior, you can provide function to change masked value and cursor position before it will be applied to the input. receives following arguments:

  1. newState (object): New input state. Contains and fields. is null on input blur or when function is called before input mount. Example:
  2. oldState (object): Input state before change. Contains and fields. is null on input focus or when function is called before input mount.
  3. userInput (string): Raw entered or pasted string. if user didn’t enter anything (e.g. triggered by deletion or rerender due to props change).
  4. maskOptions (object): Mask options. Example:
{  mask'99/99/9999',  maskChar'_',  alwaysShowMaskfalse,  formatChars{'9''','a''','*'''},  permanents2,5}

must return an object with following fields:

  1. value (string): New value.
  2. selection (object): New selection. If in argument is null, it must be null too.

Please note that executes more often than and must be pure.

To use another component instead of regular pass render function as a children. Function receives argument which contains props that aren’t used by react-input-mask’s internals. I.e. it passes down every prop except the following ones: , , , , , , , . These properties, if used, should always be passed directly to react-input-mask instead of children and shouldn’t be altered in chldren’s function.

import React from'react';import InputMask from'react-input-mask';import MaterialInput from'@material-ui/core/Input';constInput=(props)=>(<InputMaskmask="99/99/9999"value={props.value}onChange={props.onChange}>{(inputProps)=><MaterialInput{...inputProps}type="tel"disableUnderline/>}</InputMask>);constInvalidInput=(props)=>(<InputMaskmask="99/99/9999"value={props.value}>{(inputProps)=><MaterialInput{...inputProps}type="tel"disableUnderlineonChange={props.onChange}/>}</InputMask>);
import React from'react';import InputMask from'react-input-mask';classPhoneInputextendsReact.Component{render(){return<InputMask{...this.props}mask="+4\9 99 999 99"maskChar=""/>;}}

Mask for ZIP Code. Uses beforeMaskedValueChange to omit trailing minus if it wasn’t entered by user:

import React from'react';import InputMask from'react-input-mask';classInputextendsReact.Component{  state ={    value''}onChange=(event)=>{this.setState({      valueevent.target.value});}beforeMaskedValueChange=(newState,oldState,userInput)=>{var{ value }= newState;var selection =newState.selection;var cursorPosition = selection ?selection.startnull;if(value.endsWith('-')&& userInput !=='-'&&!this.state.value.endsWith('-')){if(cursorPosition ===value.length){        cursorPosition--;        selection ={ start cursorPosition, end cursorPosition };}      value =value.slice(,-1);}return{      value,      selection};}render(){return<InputMaskmask="99999-9999"maskChar={null}value={this.state.value}onChange={this.onChange}beforeMaskedValueChange={this.beforeMaskedValueChange}/>;}}

Browser’s autofill requires either empty value in input or value which exactly matches beginning of the autofilled value. I.e. autofilled value «+1 (555) 123-4567» will work with «+1» or «+1 (5», but won’t work with «+1 (___) ___-____» or «1 (555)». There are several possible solutions:

  1. Set to null and trim space after «+1» with if no more digits are entered.
  2. Apply mask only if value is not empty. In general, this is the most reliable solution because we can’t be sure about formatting in autofilled value.
  3. Use less formatting in the mask.

Please note that it might lead to worse user experience (should I enter +1 if input is empty?). You should choose what’s more important to your users — smooth typing experience or autofill. Phone and ZIP code inputs are very likely to be autofilled and it’s a good idea to care about it, while security confirmation code in two-factor authorization shouldn’t care about autofill at all.

Installation

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

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

importSelectfrom'react-select';import'react-select/dist/react-select.css';

You can also use the standalone UMD build by including and in your page. If you do this you’ll also need to include the dependencies. For example:

<scriptsrc="https://unpkg.com/react@15.6.1/dist/react.js"><script><scriptsrc="https://unpkg.com/react-dom@15.6.1/dist/react-dom.js"><script><scriptsrc="https://unpkg.com/prop-types@15.5.10/prop-types.js"><script><scriptsrc="https://unpkg.com/classnames@2.2.5/index.js"><script><scriptsrc="https://unpkg.com/react-input-autosize@2.0.0/dist/react-input-autosize.js"><script><scriptsrc="https://unpkg.com/react-select@1.2.1/dist/react-select.js"><script><linkrel="stylesheet"href="https://unpkg.com/react-select@1.2.1/dist/react-select.css">

Installation

npm install react-select-plus --save

At this point you can import react-select and its styles in your application as follows:

importSelectfrom'react-select-plus';import'react-select-plus/dist/react-select-plus.css';

You can also use the standalone build by including and in your page. (If you do this though you’ll also need to include the dependencies.) For example:

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"><script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"><script><scriptsrc="https://unpkg.com/classnames/index.js"><script><scriptsrc="https://unpkg.com/react-input-autosize/dist/react-input-autosize.js"><script><scriptsrc="https://unpkg.com/react-select-plus/dist/react-select-plus.js"><script><linkrel="stylesheet"href="https://unpkg.com/react-select-plus/dist/react-select.css">

Options

Name Type Description Example
country string initial country ‘us’ | 1
value string input state value
onlyCountries array country codes to be included
preferredCountries array country codes to be at the top
excludeCountries array array of country codes to be excluded
placeholder string custom placeholder
inputProps object props to pass into the input
Booleans Default Description
autoFormat true on/off phone formatting
disabled false disable input and dropdown
disableDropdown false disable dropdown only
disableCountryCode false
enableAreaCodes false enable local codes for all countries
enableTerritories false enable dependent territories with population of ~100,000 or lower
enableLongNumbers false
countryCodeEditable true
enableSearch false enable search in the dropdown
disableSearchIcon false hide icon for the search field
<PhoneInputinputProps={{    name'phone',    requiredtrue,    autoFocustrue}}/>
containerClass string class for container
inputClass string class for input
buttonClass string class for dropdown button
dropdownClass string class for dropdown container
searchClass string class for search field
containerStyle object styles for container
inputStyle object styles for input
buttonStyle object styles for dropdown button
dropdownStyle object styles for dropdown container
searchStyle object styles for search field
onChange onFocus onBlur onClick onKeyDown

onChange(value, country, e, formattedValue)

Country data object not returns from onKeyDown event

Data Type Description
value/event string/object event or the phone number
country data object country object { name, dialCode, countryCode (iso2) }
Name Type Description
regions array/string to show countries only from specified regions
Regions
Subregions
<PhoneInputcountry='de'regions={'europe'}/><PhoneInputcountry='us'regions={'north-america','carribean'}/>

Spanish, Deutsch, Russian, French Japanese, Chinese, Portuguese, Italian Iranian, Arabic, Indonesian

import es from'react-phone-input-2/lang/es.json'<PhoneInputlocalization={es}/>
<PhoneInputenableAreaCodes={true}enableAreaCodes={'us','ca'}enableAreaCodeStretch/>

If is added, the part of the mask with the area code will not stretch to length of the respective section of phone mask.

<PhoneInputonlyCountries={'fr','at'}masks={{fr'(...) ..-..-..', at'(....) ...-....'}}/>
<PhoneInputonlyCountries={'gr','fr','us'}areaCodes={{gr'2694','2647', fr'369','463', us'300'}}/>
defaultMask … … … … ..
alwaysDefaultMask false
prefix +
searchPlaceholder ‘search’
searchNotFound ‘No entries to show’
copyNumbersOnly true
renderStringAsFlag string
autocompleteSearch false
jumpCursorToEnd false
priority {{ca: 0, us: 1, kz: 0, ru: 1}}
enableClickOutside true
showDropdown false
defaultErrorMessage string
disableInitialCountryGuess false
<PhoneInputonlyCountries={'de','es'}localization={{de'Deutschland', es'España'}}/><PhoneInputonlyCountries={'de','es'}localization={{'Germany''Deutschland','Spain''España'}}/>
<PhoneInputonlyCountries={'fr','at'}preserveOrder={'onlyCountries','preferredCountries'}/>

Get options

You can fetch options asynchronously with the property. You can either return options directly or through a .

functiongetOptions(query){returnnewPromise((resolve, reject)=>{fetch(`https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${query}`).then(response=>response.json()).then(({ drinks })=>{resolve(drinks.map(({ idDrink, strDrink })=>({ value idDrink, name strDrink })))}).catch(reject);});}

The function runs on each search query update, so you might want to throttle the fetches. If you return a promise, the class will be applied to the main element, giving you a chance to change the appearance, like adding a spinner. The property is also available in the snapshot that is sent to your render callbacks.

Пробуем React

React изначально был спроектирован так, чтобы его можно было внедрять постепенно. Другими словами, вы можете начать с малого и использовать только ту функциональность React, которая необходима вам в данный момент. Информация в этом разделе будет полезна в любой ситуации: при первом знакомстве с React, при создании простой динамической HTML-страницы и даже при проектировании сложного React-приложения.

Онлайн-песочницы

Если вы просто хотите немного поиграть с React, попробуйте онлайн-песочницу. Например, вот простейший шаблон на CodePen, CodeSandbox, или Stackblitz.

Если вы предпочитаете работать в своём редакторе, скачайте тестовый HTML-файл, добавьте в него код и запустите на своём компьютере. При открытии тестового файла браузер преобразует JSX в обычный код на JavaScript. Такое преобразование достаточно медленно, поэтому мы рекомендуем использовать этот файл только для простых демонстрационных примеров.

Добавляем React на сайт

Вы можете добавить React на свой сайт буквально за одну минуту. После этого можно разместить на сайте несколько динамических виджетов и постепенно наращивать использование React в своём проекте.

Создаём React-приложение

Когда вы начинаете проект на React, то простая HTML-страница со script-тегами может быть лучшим вариантом. Её можно сделать за минуту.

Однако для разработки более развесистого приложения вам, скорее всего, придётся рассмотреть другие варианты настройки рабочего окружения, объединяющие в себе различные технологии. Вот несколько наборов JavaScript-инструментов, которые мы рекомендуем для создания приложения. Каждый из этих инструментов может работать практически без настройки и позволит раскрыть все возможности экосистемы React. Подробнее об инструментах.

Classes

ES6 introduced classes.

A class is a type of function, but instead of using the keyword to initiate it, we use the keyword , and the properties are assigned inside a method.

Example

A simple class constructor:

Now you can create objects using the Car class:

Example

Create an object called «mycar» based on the Car class:

Note: The constructor function is called automatically when the object is initialized.

Example

Create a method named «present»:

As you can see in the example above, you call the method by referring to the object’s method name followed by parentheses (parameters would go inside the parentheses).

Class Inheritance

To create a class inheritance, use the keyword.

A class created with a class inheritance inherits all the methods from another class:

Example

Create a class named «Model» which will inherit the methods from the «Car» class:

The method refers to the parent class.

By calling the method in the constructor method, we call the parent’s constructor method and gets access to the parent’s properties and methods.


С этим читают