Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-functional-select

Package Overview
Dependencies
Maintainers
1
Versions
100
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-functional-select

Miro-sized and micro-optimized select component for React.js

  • 2.9.4
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
912
decreased by-5.49%
Maintainers
1
Weekly downloads
 
Created
Source

react-functional-select

Micro-sized & micro-optimized select component for React.js.

Latest Stable Version Issues License Downloads

Key features:

Peer dependencies:

Overview

Essentially, this is a focused subset of react-select's API that is engineered for ultimate performance and minimal bundle size. It is built entirely using React Hooks and FunctionComponents. The primary design principal revolves around weighing the cost/benefits of adding a feature against the impact to performance & # of lines of code its addition would have.

I opted to exclude less "in-demand" features such as:

  • Preventing scroll events on the app's body if the menu is open TODO: add code example
  • Closing an open menu if the app's body is scrolled TODO: add code example

These feature would have added significant overhead to the package. In addition, if we expose the right public methods and/or callback properties, this feature should be trivial to add to wrapping components - proper decoupling and abstraction of code is key to keeping such channels open for similar customizations that can be kept out of this package.

Installation

$ npm i react-window styled-components react-functional-select
$ yarn add react-window styled-components react-functional-select

Note that you need to be on a react version that supports hooks, e.g.
react@^16.8 react-dom@^16.8 react-is@^16.8

Usage

You can find a similar example, along with others, in the storybook..

import { Select } from 'react-functional-select';
import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardHeader, CardBody, Container, SelectContainer } from './helpers/styled';

type CityOption = {
  readonly id: number;
  readonly city: string;
  readonly state: string;
};

const _cityOptions: CityOption[] = [
  { id: 1, city: 'Austin', state: 'TX' },
  { id: 2, city: 'Denver', state: 'CO' },
  { id: 3, city: 'Chicago', state: 'IL' },
  { id: 4, city: 'Phoenix', state: 'AZ' },
  { id: 5, city: 'Houston', state: 'TX' }
];

const SingleSelectDemo: React.FC = () => {
  const [isInvalid, setIsInvalid] = useState<boolean>(false);
  const [isDisabled, setIsDisabled] = useState<boolean>(false);
  const [isClearable, setIsClearable] = useState<boolean>(true);
  const [selectedOption, setSelectedOption] = useState<CityOption | null>(null);

  const getOptionValue = useCallback((option: CityOption): number => option.id, []);
  const onOptionChange = useCallback((option: CityOption | null): void => setSelectedOption(option), []);
  const getOptionLabel = useCallback((option: CityOption): string => `${option.city}, ${option.state}`, []);

  useEffect(() => {
    isDisabled && setIsInvalid(false);
  }, [isDisabled]);

  return (
    <Container>
      <Card>
        <CardHeader>
          {`Selected Option: ${JSON.stringify(selectedOption || {})}`}
        </CardHeader>
        <CardBody>
          <SelectContainer>
            <Select
              isInvalid={isInvalid}
              options={_cityOptions}
              isDisabled={isDisabled}
              isClearable={isClearable}
              onOptionChange={onOptionChange}
              getOptionValue={getOptionValue}
              getOptionLabel={getOptionLabel}
            />
          </SelectContainer>
        </CardBody>
      </Card>
    </Container>
  );
};

Properties

All properties are technically optional (with a few having default values). Very similar with react-select's API.

Note that the following non-primitive properties should be properly memoized if defined:
clearIcon, caretIcon, options, renderOptionLabel, renderMultiOptions, onMenuOpen, onOptionChange, onKeyDown, getOptionLabel, getOptionLabel, getOptionValue, onInputBlur, onInputFocus, onInputChange, onSearchChange, getIsOptionDisabled, getFilterOptionString, themeConfig

PropertyTypeDefaultDescription
inputIdstringundefinedThe id of the autosize search input
selectIdstringundefinedThe id of the parent div
ariaLabelstringundefinedAria label (for assistive tech)
isMultiboolfalseDoes the control allow for multiple selections (defaults to single-value mode)
asyncboolfalseIs the component in 'async' mode - when in 'async' mode, updates to the input search value will NOT cause the effect useMenuOptions to execute (this effect parses options into stateful value menuOptions)
autoFocusboolfalseFocus the control following initial mount of component
isLoadingboolfalseIs the select in a state of loading - shows loading dots animation
isInvalidboolfalseIs the current value invalid - control recieves invalid styling
inputDelaynumberundefinedThe debounce delay in for the input search (milliseconds)
isDisabledboolfalseIs the select control disabled - recieves disabled styling
requiredboolfalseIs the select control required - applied to the input element. When true, the optionally specified CSS from the themeConfig.input.cssRequired field will be applied to the input element.
placeholderstringSelect option..Placeholder text for the select value
menuWidthReactText100%Width of the menu
menuItemSizenumber35The height of each option in the menu (px)
isClearableboolfalseIs the select value clearable
noOptionsMsgstringNo optionsThe text displayed in the menu when there are no options available
loadingMsgstringLoading...The text displayed in the menu when isLoading === true
clearIconReactNode OR ((state: Partial<IndicatorIconsProps>) => ReactNode)undefinedCustom clear icon node - state forwarded to a function is { menuOpen, isLoading, isInvalid, isDisabled }
caretIconReactNode OR ((state: Partial<IndicatorIconsProps>) => ReactNode)undefinedCustom caret icon node - state forwarded to a function is { menuOpen, isLoading, isInvalid, isDisabled }
loadingNodeReactNodeundefinedCustom loading node
optionsarray[]The menu options
isSearchablebooltrueWhether to enable search functionality or not
hideSelectedOptionsboolfalseHide the selected option from the menu (if undefined and isMulti = true, then defaults to true)
openMenuOnClickbooltrueIf true, the menu can be toggled by clicking anywhere on the select control; if false, the menu can only be toggled by clicking the 'caret' icon on the far right of the control
menuMaxHeightnumber300Max height of the menu element - this effects how many options react-window will render
menuOverscanCountnumber1correlates to react-window property overscanCount: The number of items (options) to render outside of the visible area. Increasing the number can impact performance, but is useful if the option label is complex and the renderOptionLabel prop is defined
itemKeySelectorReactTextundefinedIf defined, will use the property in your original options as each option's key, rather than the parsed stateful value menuOptions index (this needs to be a unique property - so properties such as id or value). This relates to the itemKey property in dependency react-window - more info here
menuScrollDurationnumber300Duration of scroll menu into view animation
addClassNamesboolfalseShould static classNames be generated for container elements (enable if styling using CSS stylesheets)
ariaLabelledBystringundefinedHTML ID of an element that should be used as the label (for assistive tech)
openMenuOnFocusboolfalseOpen the menu when the select control recieves focus
initialValueanyundefinedInitial select value
tabSelectsOptionbooltrueSelect the currently focused option when the user presses tab
blurInputOnSelectboolfalseRemove focus from the input when the user selects an option (useful for dismissing the keyboard on touch devices)
closeMenuOnSelectbooltrueClose the select menu when the user selects an option
isAriaLiveEnabledboolfalseEnables visually hidden div that reports stateful information (for assistive tech)
scrollMenuIntoViewbooltruePerforms animated scroll to show menu in view when menu is opened (if there is room to do so)
backspaceClearsValuebooltrueRemove the currently focused option when the user presses backspace
filterMatchFrom'any' OR 'start''any'Position in stringified option to match search input
menuPosition'top' OR 'auto' OR 'bottom''bottom'Determines where menu will be placed in relation to the control - 'auto' will first check if menu has space to open below the control, otherwise it will open above the control.
filterIgnoreCasebooltrueSearch input ignores case of characters when comparing
filterIgnoreAccentsboolfalseSearch input will strip diacritics from string before comparing
onMenuOpen(...args: any[]): voidundefinedCallback function executed after the menu is opened
onMenuClose(...args: any[]): voidundefinedCallback function executed after the menu is closed
onOptionChange(data: any): voidundefinedCallback function executed after a new option is selected
onKeyDown(e: KeyboardEvent<HTMLDivElement>, input?: string, focusedOption?: FocusedOption): voidundefinedCallback function executed onKeyDown event
getOptionLabel(data: any): ReactTextundefinedResolves option data to React.ReactText to be displayed as the label by components (by default will use option.label)
getOptionValue(data: any): ReactTextundefinedResolves option data to React.ReactText to compare option values (by default will use option.value)
onInputBlur(e: FocusEvent<HTMLInputElement>): voidundefinedHandle blur events on the search input
onInputFocus(e: FocusEvent<HTMLInputElement>): voidundefinedHandle focus events on the search input
onInputChange(value: string): voidundefinedHandle change events on the search input
onSearchChange(value: string): voidundefinedCallback executed after the debounced search input value is persisted to the component's state - if no debounce is defined via the inputDelay property, it probably makes more sense to use onInputChange instead.
renderOptionLabel(data: any): ReactNodeundefinedFormats option labels in the menu and control as JSX.Elements or React Components (by default will use getOptionLabel)
renderMultiOptions(params: MultiParams): ReactNodeundefinedAllows for customization as to how multi-select options should be formatted. The MultiParams contains the array of selected options { selected: Array<{ data: any, value: ReactText, label: ReactText}>, renderOptionLabel: (data: any): ReactNode }. Left and right arrow key navigation will also be disabled when this property is defined.
getIsOptionDisabled(data: any): booleanundefinedWhen defined will evaluate each option to determine whether it is disabled or not (if not specified, each option will be evaluated as to whether or not it contains a property of isDisabled with a value of true)
getFilterOptionString(option: any): stringundefinedWhen defined will take each option and generate a string used in the filtering process (by default, will use option.label)
themeConfigPartial<DefaultTheme>undefinedObject that takes specified property key-value pairs and merges them into the theme object

Inspiration

This project was inspired by react-select.

License

MIT licensed. Matt Areddia © 2019.

Keywords

FAQs

Package last updated on 25 Nov 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc