1.0.0-beta.28 • Published 4 years ago

tiendeo-react-functional-select v1.0.0-beta.28

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

react-functional-select

Micro-sized & micro-optimized select component for ReactJS

Latest Stable Version Travis NPM license

Inspiration

This project was inspired by react-select. If you need some features not provided, I suggest checking that package out.

Install

# npm
npm i react-window styled-components react-functional-select

# Yarn
yarn add react-window styled-components react-functional-select

Overview

Essentially, this is a subset of react-select's API, engineered for ultimate performance and minimal dependency footprint. It is built entirely using React Hooks and FunctionComponents. In addition, most of the code I was able to roll myself, so there are minimal peer dependencies to worry about:

  • react-window leveraged for integrated data virtualization/windowing (easily handles data-sets numbering in the tens of thousands with minimal-to-no impact on normally resource-intensive actions like keying and searching).
  • styled-components to handle dynamic, extensible styling via CSS-in-JS (there is also the option to generate className attributes for legacy stylesheets as a fall-back option).

While still a work in progress, its current state should be suitable for many use-cases. Please feel free to contribute and/or make suggestions - specificaly, in the following areas:

  • Additional flexibility to the styling system. Currently handles simple-to-mid level complexity scenarios via styled-component's overrideable ThemeProvider. As a fallback, you generate static className attributes on container nodes.
  • The ability to handle complex, multi-select scenarios (while keeping with the theme of optimal performance in as few lines of code as possible).

Usage

Condensed BasicProps.story.tsx

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

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

const _options: 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 BasicProps: 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 onOptionChange = useCallback((option: CityOption | null): void => {
    setSelectedOption(option);
  }, []);
  
  const getOptionValue = useCallback((option: CityOption): number => (option.id), []);
  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
              options={_options}
              isInvalid={isInvalid}
              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 API.

PropertyTypeDefaultDescription
inputIdstringundefinedThe id of the autosize search input
selectIdstringundefinedThe id of the parent div
idSuffixstringundefinedGUID that gets appended to inputId and selectId - when specified, generates ids for each individual option
ariaLabelstringundefinedAria label (for assistive tech)
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
placeholderstringSelect option..Placeholder text for the select value
menuWidthReact.ReactText100%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
clearIconReact.ReactNodeundefinedCustom clear icon
caretIconReact.ReactNodeundefinedCustom caret icon
optionsarray[]The menu options
isSearchablebooltrueWhether to enable search functionality or not
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.
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
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
tabSelectsOptionbooltrueSelect the currently focused option when the user presses tab
blurInputOnSelectbooltrue IF device is touch-enabled ELSE falseRemove 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
filterIsCaseSensitiveboolfalseSearch input takes case of option labels into account
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
onKeyDownReact.KeyboardEventHandler\<HTMLDivElement>undefinedCallback function executed onKeyDown event
getOptionLabel(data: any) => React.ReactTextundefinedResolves option data to React.ReactText to be displayed as the label by components (by default will use option.label)
getOptionValue(data: any) => React.ReactTextundefinedResolves option data to React.ReactText to compare option values (by default will use option.value)
onInputBlurReact.FocusEventHandler\<HTMLInputElement>undefinedHandle blur events on the search input
onInputFocusReact.FocusEventHandler\<HTMLInputElement>undefinedHandle focus events on the search input
renderOptionLabel(data: any) => React.ReactNodeundefinedFormats option labels in the menu and control as JSX.Elements or React Components (by default will use getOptionLabel)
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