Giter VIP home page Giter VIP logo

based-ghost / react-functional-select Goto Github PK

View Code? Open in Web Editor NEW
193.0 2.0 11.0 38.96 MB

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

Home Page: https://master--625676b6922472003af898b4.chromatic.com

License: MIT License

JavaScript 1.97% TypeScript 95.34% HTML 2.67% Shell 0.02%
react select dropdown multi-select functional styled-components performance windowing react-components virtualization react-functional-select

react-functional-select's Introduction

NPM npm downloads Issues License style: styled-components

react-functional-select

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

See the accompanying Interactive Storybook UI Site for live demos and detailed docs.

Key features:

  • Extremely lightweight: ~6 kB (gzipped)!
  • Advanced features like async mode, portal support, animations, and option virtualization
  • Fully-featured & customizable: API comparable to react-select
  • Engineered for ultimate performance: effortlessly scroll, filter, and key through datasets numbering in the tens of thousands using react-window + performance-first code. Demo of handling 50,000 options here!
  • Extensible styling API with styled-components
  • Accessible

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 with the React Hooks API (no legacy class components). The primary design principal revolves around weighing the cost/benefits of adding a feature against the impact to performance and/or number of lines of code its addition would have.

Any expected features not in the current API is likely due to the reason that such features 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. Please, feel free to offer enhancement ideas with/without technical solutions.

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 (>= 16.8.6)

Usage

import { Select } from 'react-functional-select';
import React, { useState, useEffect, useCallback, type ComponentProps } from 'react';
import { Card, CardHeader, CardBody, Container, SelectContainer } from '../shared/components';

type SelectProps = ComponentProps<typeof Select>;

type Option = Readonly<{
  id: number;
  city: string;
  state: string;
}>;

const CITY_OPTIONS: Option[] = [
  { 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 SingleSelect: React.FC<SelectProps> = ({ isDisabled }) => {
  const [isInvalid, setIsInvalid] = useState<boolean>(false);
  const [selectedOption, setSelectedOption] = useState<Option | null>(null);

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

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

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

export default SingleSelect;

Properties

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

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

Property Type Default Description
inputId string undefined The id of the autosize search input control
selectId string undefined The id of the parent select container element
menuId string undefined The id of the menu container element
ariaLabel string undefined Aria label (for assistive tech)
isMulti bool false Does the control allow for multiple selections (defaults to single-value mode)
async bool false Is 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)
autoFocus bool false Focus the control following initial mount of component
lazyLoadMenu bool false If true, the menu (wrapper & virtualized list components) will rendered in DOM only when menuOpen state is true
isLoading bool false Is the select in a state of loading - shows loading dots animation
isInvalid bool false Is the current value invalid - control recieves invalid styling
inputDelay number undefined The debounce delay in for the input search (milliseconds)
pageSize number 5 Number of options to jump in menu when page{up
isDisabled bool false Is the select control disabled - recieves disabled styling
required bool false Is 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.
placeholder string Select option.. Placeholder text for the select value
menuWidth string number 100%
menuItemSize number 35 The height of each option in the menu (px)
isClearable bool false Is the select value clearable
noOptionsMsg string No options The text displayed in the menu when there are no options available (to hide menu when search returns no items, set to null or '')
loadingMsg string Loading.. The text displayed in the menu when isLoading === true
clearIcon ReactNode OR ((state: any) => ReactNode) undefined Custom clear icon node - state forwarded to a function is { menuOpen, isLoading, isInvalid, isDisabled }
caretIcon ReactNode OR ((state: any) => ReactNode) undefined Custom caret icon node - state forwarded to a function is { menuOpen, isLoading, isInvalid, isDisabled }
loadingNode ReactNode undefined Custom loading node
options array [] The menu options
isSearchable bool true Whether to enable search functionality or not
hideSelectedOptions bool false Hide the selected option from the menu (if undefined and isMulti = true, then defaults to true)
openMenuOnClick bool true If 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
menuMaxHeight number 300 Max height of the menu element - this effects how many options react-window will render
menuOverscanCount number 1 correlates 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
itemKeySelector string number undefined
menuScrollDuration number 300 Duration of scroll menu into view animation
menuItemDirection 'ltr' OR 'rtl' 'ltr' The direction of text for each menu option and position of the menu's scroll bar (react-window's direction prop)
ariaLabelledBy string undefined HTML ID of an element that should be used as the label (for assistive tech)
ariaLive 'off' OR 'polite' OR 'assertive' 'polite' Used to set the priority with which screen reader should treat updates to live regions (translates to aria-live attribute)
openMenuOnFocus bool false Open the menu when the select control recieves focus
initialValue any undefined Initial select value
tabSelectsOption bool true Select the currently focused option when the user presses tab
blurInputOnSelect bool false Remove focus from the input when the user selects an option (useful for dismissing the keyboard on touch devices)
closeMenuOnSelect bool true Close the select menu when the user selects an option
isAriaLiveEnabled bool false Enables visually hidden div that reports stateful information (for assistive tech)
scrollMenuIntoView bool true Performs animated scroll to show menu in view when menu is opened (if there is room to do so)
backspaceClearsValue bool true Remove 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.
filterIgnoreCase bool true Search input ignores case of characters when comparing
filterIgnoreAccents bool false Search input will strip diacritics from string before comparing
onMenuOpen (...args: any[]) => void undefined Callback function executed after the menu is opened
onMenuClose (...args: any[]) => void undefined Callback function executed after the menu is closed
onOptionChange (data: any) => void undefined Callback function executed after a new option is selected
onKeyDown (e: KeyboardEvent, input?: string, focusedOption?: FocusedOption) => void undefined Callback function executed onKeyDown event
getOptionLabel (data: any) => string number undefined
getOptionValue (data: any) => string number undefined
onInputBlur (e: FocusEvent) => void undefined Handle blur events on the search input
onInputFocus (e: FocusEvent) => void undefined Handle focus events on the search input
onInputChange (value: string) => void undefined Handle change events on the search input
onSearchChange (value: string) => void undefined Callback 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) => ReactNode undefined Formats option labels in the menu and control as JSX.Elements or React Components (by default will use getOptionLabel)
renderMultiOptions (params: any) => ReactNode undefined Allows for customization as to how multi-select options should be formatted. The MultiParams contains the array of selected options `{ selected: Array<{ data: any, value: string
getIsOptionDisabled (data: any) => boolean undefined When 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) => string undefined When defined will take each option and generate a string used in the filtering process (by default, will use option.label)
themeConfig Partial<DefaultTheme> undefined Object that takes specified property key-value pairs and merges them into the theme object
menuPortalTarget Element undefined Whether the menu should use a portal, and where it should attach
memoOptions bool false Whether to memoize each Option component

Inspiration

This project was inspired by react-select.

License

MIT licensed. Copyright (c) Matt Areddia 2022.

react-functional-select's People

Contributors

based-ghost avatar brettm12345 avatar brightpixels avatar dependabot[bot] avatar michal-wrzosek avatar stephenwf 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

react-functional-select's Issues

initialValue prop not working?

Hi, I have initialValue set and it's not using it.

        <Select
            initialValue={maxPlayers}
            options={[1, 2, 3, 4, 5, 6, 7, 8]}
            onOptionChange={setMaxPlayers}
            getOptionValue={opt => opt}
            getOptionLabel={opt => opt}
          />

I even hard-coded it to initialValue={2} without success. Am I doing something wrong?

No tag / release for version 5.0.0

Version 5.0.0 has been released on NPM, but there is no tag for this version, and no Github Release or changelog.

Is this version legit? Could you add a release or a Changelog so we know what changed?

Suggestion: open dropdown at top when don't have enough place

In some cases (ex: select language) we need to place the select at bottom of the page, would be great to open the dropdown at top when bottom don't have enough place.

For example if we removed the min-height of container in your storybook demo:
0

Not rendered options

Hi. sometimes when the menu is opened, some options are not rendered
image

<SelectStyled lazyLoadMenu={true} themeConfig={themeConfig} ref={selectRef} isClearable options={options} isDisabled={isDisabled} onOptionChange={onChange} placeholder={placeholder} isInvalid={validation} openMenuOnClick={onClick} initialValue={value} isLoading={isLoading} />

Cannot add styles for Single Value

Hello,

Unless I'm mistaken, there is no way to add styles for the Single Value component. Based on the source code:

const SINGLE_VALUE_BASE_STYLE = css`
  top: 50%;
  overflow: hidden;
  position: absolute;
  white-space: nowrap;
  box-sizing: border-box;
  text-overflow: ellipsis;
  transform: translateY(-50%);
`;

const SingleValue = styled.div`
  ${SINGLE_VALUE_BASE_STYLE}
  max-width: calc(100% - 0.5rem);
`;

There is no theme extension for Single Value. What I'm trying to achieve is to change to "top" property, basically.

Screenshot 2021-11-24 at 20 07 01

Notice the position of the Label and Input value vs. the Single Value position.

Thank you!

Is sortable multi-select supported?

Hi,
For a huge number of options in the select list, I think a sortable feature would be useful. As I can see from the docs that the library doesn't support this feature itself; however, I wonder if it is possible to use this library with other library that supports sortable, for example react-sortable-hoc? Or if there is other possible implementation for sortable feature, I'd appreciate if you could show me.
Thanks in advance!

I can't customize control container as much as I like

I've been having some issues with customization for the last couple of days. I tried and failed to do 2 things.

  1. Give a custom height to the select container which is lower than its default value. I can change its font size by applying css to control container but i just cannot decrease the select container's default height. Is there a configuration option like menuItemSize that applies to the selector that I am potentially missing?

  2. I need to apply custom style to the control box when the menu is toggled. The problem is clicking on the component focuses the select container instead of the control container so .rfs-control-container:focus doesn't get applied when the component is clicked. I tried the following scss rule but apparently it doesn't work either.

.rfs-select-container {
	&:focus {
		.rfs-control-container {
			background-color: #fff !important;
			box-shadow: 0 2.5px 5px 0 rgba(224, 228, 238, 0.75);
		}
	}
}

I'd appreciate some assistance.

Capturing input value and using it as the selected option

Hello, I am trying to implement the react-functional-select component into an application that I am working on, I am wondering if there is a way to capture the input from the user and be able to use that value as the selected option. Is this part of the functionality that is built into this component?

I have a list of options that exist already, my goal is to be able to capture the input from the user in the case that what they typed in does not match any of the options that are available in the predefined set.

Custom cursor style on control and/or menu

Hello, I have reviewed the documentation and the code, but I have not found a way to change the cursor style.

Another possibility is something similar to renderOptionLabel, but for control as well.

Thanks!

Support for VariableSizeList

I have a case where I render items which have optional subtext (see example below). In the case where the subtext is not available I'd like to show a smaller sized menu item.

Currently, FixedSizeList is used, which doesn't support this behaviour. Could VariableSizeList be used instead?

Screen Shot 2021-04-26 at 8 47 54 AM

Missing types

In the published package the ./src/types folder doesn't appear to be included in the ./dist folder.

If you check Select.d.ts you can see it importing from ./types which doesn't exist in the published model.

Introduced in: 2.3.3 (source)
Working in: 2.3.2 (source)
Still missing in 3.3.3 (source)

A possible fix would be to rename the index.d.ts and styled.d.ts to index.ts and styled.ts respectively. The other would be to use something like copy-files to grab the *.d.ts into the dist folder.

How to set selected option from outside?

Version: 2.9.4

I'm trying to set the selected option / value of the Select from outside of the component. It seems that when I do that, the Select component fires onOptionChange with the previous (still current?) value which (probably?) overrides the new value that was just passed in.

Code:

import React, { useState } from 'react'
import { Select } from 'react-functional-select'

const initialOptions = [
  { value: 0, label: 'Abc' },
  { value: 1, label: 'Bcd' },
  { value: 2, label: 'Cde' }
]

export default () => {
  const [options, setOptions] = useState(initialOptions)
  const [value, setValue] = useState(null)
  console.log('value', value)

  return <>
    <Select options={options}
            initialValue={value}
            onOptionChange={option => console.log('onOptionChange', option)}
    />
    <button onClick={() => {
      const newOption = { value: 3, label: 'New' }
      setOptions([newOption, ...options])
      setValue(newOption)
    }}>
      Set new value
    </button>
  </>
}

Expectations:

  • When I click on the "Set new value" button, I expect to have the option with label "New" selected.

Actual behavior:

  • The "New" option is not selected.

Console reveals that when I click on the button, the onOptionChange callback is fired with the previously selected option (or null if none was selected). One might guess that this is an indication that the newly set value is immediately afterwards overridden by the previous value.

Console output:

value null
... now click the button...
value {value: 3, label: "New"}
onOptionChange null

(All the code examples I found have the selected option assigned solely from the argument passed by the onOptionChange callback, including issue #5.)

Some bugs I spotted...

  1. If hideSelectedOptions is set to true, all other options disappear after an option is selected. (Might be related to search functionality)
  2. If hideSelectedOptions is set to false, rfs-option-selected css class is applied to all options after an option is selected.
  3. onOptionChange does not fire again after an option is selected. Note that this was the case when hideSelectedOptions was set to false, since there is currently no way to fire it twice while it is set to true afaik.

Code is pretty much like the following. If my code is wrong, feel free to let me know.

const getOptionLabel = useCallback((option: SomeObject): string => option.text, []);
const onOptionChange = useCallback((option: SomeObject | null): void => {
	console.log(option);
	if (!option) return;
	setSomeState(prevState => {
		return { ...prevState, id: option.id };
	});
}, []);

<Select
	options={someObjectArray}
	isDisabled={!!someValue}
	ref={selectRef}
	placeholder="some text"
	onOptionChange={onOptionChange}
	getOptionLabel={getOptionLabel}
	addClassNames={true}
	hideSelectedOptions={true}
	menuItemSize={30}
	blurInputOnSelect={true}
	noOptionsMsg="some text"
	themeConfig={...}
        onMenuClose={() => selectRef.current.blur()}
/>

Controlled input value

I don't see an obvious way to control the value of the select input. This is necessary for at least me, since I am using controlled inputs in react-form-hooks.

Am I missing something?

Order of multi-select tags not preserved.

There seems to be an issue with the order of tags when using multi-select.

If I choose c, b, a (in that order) from menuOptions which are by default in this order (a, b, c & d), if the data is preserved and the component is re-loaded, the tags are in the order of the menuOptions (a, b, c) and NOT (c, b, a).

The issue arises in this function:

(It's the final reduce function).

export function validateSetValueParam(

I am not confident in changing this function as I'm not sure about the repercussions that I'm unaware of.

Accessibility issue/question

Hi,
I've notice that the component is not tab selectable and so it will interfere with accessibility focused software. I've also noted that you've set the tabindex to -1 on the input used to filter.

  1. Do you have a plan to address accessibility issues (this one in particular)?
  2. Is there a reason for the "-1" as value for tabindex?
  3. Would you consider the reset/clear button to be part of the tab index flow too?

AJAX/Fetch-powered dropdown?

I’m looking at the API, and I can’t figure out relevant options, but is it possible to build a dropdown that will fetch options via XHR/fetch as a user types input?

Of all the libraries I’ve explored, I love this one for a few reasons —

  1. It is super lightweight.
  2. It performs really well.
  3. The API and the examples are all well laid out and thoughtful.

I’d absolutely love to use this library to build my dropdowns, but currently I’m looking for a component that will let me build a search-as-you-type dropdown.

Got an error: 'Cannot read properties of undefined (reading 'withConfig')' during the testing with RTL

Hi!

I updated from 3.3.3 to 5.0.0 v of the react-functional-select.

After this, I got an error:
image

This error occurred when the component with Select loaded before tests started. And I have no idea what happened and how to solve it.
I use CRA, RTL, and Typescript.

Environment

Node: 16.17.0
npm: 8.15.0

npmPackages:
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1",
"react-functional-select": "^5.0.0",
"styled-components": "^5.3.5",
"typescript": "^4.7.4",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^14.2.1",
"jest-styled-components": "^7.0.8",

And using:

const CustomSelect = (props: SelectProps) => {  
   // ....
    
        const getCaretIcon = ({ menuOpen }: IconState) => (
            <StyledCaretIconSelect active={menuOpen}>
                <CaretIcon className="select-caret-icon" />
            </StyledCaretIconSelect>
        );
        
        const getCrossIcon = () => (
            <>
                <CrosstIcon className="select-cross-icon" />
                <StyledSelectIconsDevider className="select-devider" />
            </>
        );

    const handleOnChange = useCallback((option: OptionData) =>  onChange(option), []);

    const getOptionValue = useCallback(
        (option: OptionData): number | string =>
            handleOptionValue(option),
        [],
    );

    const getOptionLabel = useCallback(
        (option: OptionData): number | string =>
            handleOptionLabel(option),
        [],
    );


    return (
            <Select
                initialValue={value}
                options={options}
                isInvalid={isInvalid}
                isSearchable={isSearchable}
                isClearable={isClearable}
                isDisabled={isDisabled}
                onOptionChange={handleOnChange}
                getOptionValue={getOptionValue}
                getOptionLabel={getOptionLabel}
                caretIcon={getCaretIcon}
                clearIcon={getCrossIcon}
                themeConfig={ThemeSelectFilter}
                required={required}
                placeholder={placeholder}
                hideSelectedOptions={false}
                menuItemSize={selectMenuItemSize}
                menuWidth={menuWidth}
            />
    );
};

export default CustomSelect;

and theme:

const ThemeSelectFilter: Partial<DefaultTheme> = {
    color: {
        border: 'transparent',
        danger: `${COLORS.warning}`,
        dangerLight: 'rgb(213 66 54 / 25%)',
        disabled: `${COLORS.background.disabled}`,
        placeholder: `${COLORS.text.light}`,
        iconSeparator: 'transparent',
    },
    icon: {
        padding: 0,
        css: css`
            svg {
                fill: ${COLORS.text.light};
            }

            .select-caret-icon {
                margin-bottom: 2px;
                width: 12px;
                height: 6px;
            }

            .select-cross-icon {
                margin-right: 10px;
                width: 10px;
                height: 10px;
            }
        `,
    },
    control: {
        minHeight: '20px',
        borderWidth: '1px',
        boxShadow: '0 0 0 0.18rem',
        boxShadowColor: 'transparent',
        focusedBorderColor: 'transparent',
        padding: '0px 10px 0px 3px',
        css: css`
            font-weight: 600;
            cursor: pointer;
        `,
    },
    menu: {
        padding: '8px',
        borderRadius: `${SIZES.border.radius}`,
        boxShadow: '0 2px 10px #00000029',
        option: {
            selectedColor: `${COLORS.text.main}`,
            selectedBgColor: 'transparent',
            padding: '5px 7px',
            focusedBgColor: 'transparent',
        },
    },
    noOptions: {
        fontSize: `${SIZES.typography.body1}`,
        margin: '0',
        color: `${COLORS.text.light}`,
        padding: '5px 7px',
    },
};

But, I also got this error even without theming.

Mount the dropdown menu outside the parent div

Hi,

I am rendering the select within another component - that requires overflow: hidden

This means that I cannot see the dropdown after opening it.

As such, do you think it is possible to add portaling / Overlay etc. to the dropdown to get around this issue?

I note that React select has a menuPortalTarget prop - so something similar would be amazing:

menu position when there is not enough space

First of all, congratulations on such a beautiful component. I am very attracted to the way you have implemented the search without delay in the DOM.

I have a doubt...
Will the option of automatic or manual positioning of the menu be implemented when there is not enough space?

An idea: react-select

Thank you!

Feedback after first test

Just a raw feedback after 2 hours spent on testing component. Promising but fixes needed (imho).

  1. Options cannot be passed as readable meaning they are prone to mutation. A no no since we want functional coding style.
  2. No way to render icon in label (only allows string type).
  3. onOptionChange is documented as
onOptionChange(data: any) => void - executed after an option is selected or removed

is that really correct "or option removed" - the options list should not be mutable?
4. I found this lib when trying to find a minimalistic library with first class support for styled-components. A little disappointed, having to edit themeProvider as object and even then it is quite difficult to get to some styling properties, e.g. I want to reduce focused border width.
5. Cannot find a way to support cursor: pointer over control.
6. I see no possibility to hide "select options" text inside empy select
[edit: set placeholder=""] - hackish though

Just my quick tidbits. Good work, keep it up!

Typescript error

Error:Error:line (9)TS7016: Could not find a declaration file for module 'react-functional-select'.
Try npm install @types/react-functional-select if it exists or add a new declaration (.d.ts) file containing declare module 'react-functional-select';

Filter by startsWith instead of contains the typed value

Is it possible to add a prop to filter by startsWith instead of the current filter?

If I have these list of words:

  • strike
  • ancestor
  • indication
  • recognize
  • dilute
  • man
  • fog
  • rise
  • grudge
  • recognize

Currently, if I search ri the result is:

  • strike
  • rise

If we apply the new proposed filter the result is:

  • rise

Thanks

Separate render prop for control vs menu

Is there a plan to support a separate render prop for the selected option in the control vs the menu? Currently renderOptionLabel is applied to both.

I am rendering custom menu items with additional subtext and an icon, it doesn't make sense for me to display these extra things in the control, I just want the main piece of text. In the example below, I would like to be able to only render Denver in the control

Screen Shot 2021-04-26 at 8 44 19 AM

Something like renderControlLabel to go along with the current renderOptionLabel?

To styling with different states

Hello, may I know how to styling for different states? For example if I use a custom component as caret icon, how to set something like rotate(180deg) for it when menu is opened?

Below is what react select do (state.isSelected / state.isDisabled):

const customStyles = {
  option: (provided, state) => ({
    ...provided,
    borderBottom: '1px dotted pink',
    color: state.isSelected ? 'red' : 'blue',
    padding: 20,
  }),
  control: () => ({
    // none of react-select's styles are passed to <Control />
    width: 200,
  }),
  singleValue: (provided, state) => {
    const opacity = state.isDisabled ? 0.5 : 1;
    const transition = 'opacity 300ms';

    return { ...provided, opacity, transition };
  }
}

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.