Convert Figma logo to code with AI

alexkuz logoreact-input-enhancements

Set of enhancements for input control

1,375
68
1,375
25

Top Related Projects

The Select Component for React.js

12,045

🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

A set of React components implementing Google's Material Design specification with the power of CSS Modules

Bootstrap components built with React

WAI-ARIA compliant React autocomplete (combobox) component

Quick Overview

React-input-enhancements is a library that provides enhanced input components for React applications. It offers various features like autocompletion, dropdown menus, and masked inputs, designed to improve user experience and simplify form handling in React projects.

Pros

  • Enhances standard input components with advanced functionality
  • Customizable and flexible, allowing for easy integration into existing projects
  • Provides a consistent API across different input types
  • Improves user experience with features like autocompletion and masked inputs

Cons

  • May have a learning curve for developers unfamiliar with the library's API
  • Could potentially increase bundle size if not used efficiently
  • Limited documentation and examples for some advanced use cases
  • Might require additional styling to match specific design requirements

Code Examples

  1. Basic Autocomplete Input:
import { Autocomplete } from 'react-input-enhancements';

const MyComponent = () => (
  <Autocomplete
    options={['Apple', 'Banana', 'Cherry']}
    value={value}
    onChange={handleChange}
  />
);
  1. Masked Input for Phone Numbers:
import { MaskedInput } from 'react-input-enhancements';

const MyComponent = () => (
  <MaskedInput
    mask="+1 (###) ###-####"
    value={phoneNumber}
    onChange={handlePhoneChange}
  />
);
  1. Dropdown Menu with Custom Rendering:
import { Dropdown } from 'react-input-enhancements';

const MyComponent = () => (
  <Dropdown
    options={[
      { value: 'option1', label: 'Option 1' },
      { value: 'option2', label: 'Option 2' },
    ]}
    value={selectedOption}
    onChange={handleOptionChange}
    renderOption={(option) => <div className="custom-option">{option.label}</div>}
  />
);

Getting Started

To use react-input-enhancements in your project, follow these steps:

  1. Install the package:

    npm install react-input-enhancements
    
  2. Import and use the components in your React application:

    import React, { useState } from 'react';
    import { Autocomplete } from 'react-input-enhancements';
    
    const MyComponent = () => {
      const [value, setValue] = useState('');
    
      return (
        <Autocomplete
          options={['Option 1', 'Option 2', 'Option 3']}
          value={value}
          onChange={(newValue) => setValue(newValue)}
        />
      );
    };
    
    export default MyComponent;
    
  3. Customize the components as needed using the provided props and styling options.

Competitor Comparisons

The Select Component for React.js

Pros of react-select

  • More comprehensive and feature-rich, offering advanced functionalities like multi-select, async loading, and custom styling
  • Larger community and better documentation, making it easier to find solutions and integrate
  • Regular updates and maintenance, ensuring compatibility with newer React versions

Cons of react-select

  • Larger bundle size due to its extensive feature set, which may impact performance in smaller projects
  • Steeper learning curve for customization, especially for developers new to the library
  • May be overkill for simple use cases, where a lighter solution could suffice

Code Comparison

react-select:

import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
];

<Select options={options} />

react-input-enhancements:

import { Autocomplete } from 'react-input-enhancements';

const options = ['Chocolate', 'Strawberry', 'Vanilla'];

<Autocomplete options={options}>
  {props => <input {...props} />}
</Autocomplete>

While both libraries provide similar functionality, react-select offers a more declarative API with built-in styling, whereas react-input-enhancements focuses on enhancing existing input elements with minimal overhead.

12,045

🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

Pros of downshift

  • More actively maintained with frequent updates and bug fixes
  • Offers greater flexibility and customization options
  • Provides better accessibility features out-of-the-box

Cons of downshift

  • Steeper learning curve due to its more complex API
  • Requires more setup and configuration for basic use cases

Code Comparison

react-input-enhancements:

<Autocomplete
  options={['Apple', 'Banana', 'Cherry']}
  value={selectedFruit}
  onChange={handleChange}
/>

downshift:

<Downshift
  onChange={selection => console.log(selection)}
  itemToString={item => (item ? item.value : '')}
>
  {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem }) => (
    <div>
      <input {...getInputProps()} />
      {isOpen && (
        <div>
          {['Apple', 'Banana', 'Cherry'].map((item, index) => (
            <div {...getItemProps({ key: item, index, item })}>
              {item}
            </div>
          ))}
        </div>
      )}
    </div>
  )}
</Downshift>

The code comparison shows that downshift requires more setup but offers greater control over the rendering and behavior of the component. react-input-enhancements provides a simpler API for basic use cases but with less flexibility.

A set of React components implementing Google's Material Design specification with the power of CSS Modules

Pros of react-toolbox

  • Comprehensive UI component library with a wide range of pre-built components
  • Follows Material Design principles, ensuring a consistent and modern look
  • Active community and regular updates

Cons of react-toolbox

  • Larger bundle size due to the extensive component library
  • Steeper learning curve for customization and theming
  • May require additional configuration for optimal performance

Code Comparison

react-toolbox:

import { Button, IconButton } from 'react-toolbox/lib/button';

<Button label="Hello World" raised primary />
<IconButton icon="favorite" />

react-input-enhancements:

import { Autocomplete } from 'react-input-enhancements';

<Autocomplete
  options={['Apple', 'Banana', 'Orange']}
  value={this.state.value}
  onChange={this.handleChange}
/>

react-toolbox provides a more comprehensive set of UI components, while react-input-enhancements focuses specifically on enhancing input fields. react-toolbox offers a cohesive design system based on Material Design, whereas react-input-enhancements provides more flexibility for custom styling. The code examples demonstrate the difference in component usage and complexity between the two libraries.

Bootstrap components built with React

Pros of react-bootstrap

  • Comprehensive set of pre-built components based on Bootstrap
  • Large and active community with frequent updates
  • Extensive documentation and examples

Cons of react-bootstrap

  • Larger bundle size due to the full Bootstrap framework
  • Less flexibility for custom styling compared to more focused libraries
  • Steeper learning curve for developers unfamiliar with Bootstrap

Code Comparison

react-bootstrap:

import { Button, Form } from 'react-bootstrap';

<Form>
  <Form.Group controlId="formBasicEmail">
    <Form.Label>Email address</Form.Label>
    <Form.Control type="email" placeholder="Enter email" />
  </Form.Group>
  <Button variant="primary" type="submit">Submit</Button>
</Form>

react-input-enhancements:

import { Input } from 'react-input-enhancements';

<Input
  defaultValue=""
  onChange={value => console.log(value)}
  autoComplete={['apple', 'banana', 'cherry']}
/>

react-bootstrap provides a more comprehensive set of components with built-in styling, while react-input-enhancements focuses on enhancing input functionality with features like autocomplete. The choice between the two depends on project requirements, with react-bootstrap offering a full UI framework and react-input-enhancements providing specialized input enhancements.

WAI-ARIA compliant React autocomplete (combobox) component

Pros of react-autocomplete

  • Officially maintained by the React team, ensuring compatibility and long-term support
  • Lightweight and focused solely on autocomplete functionality
  • Highly customizable with extensive documentation

Cons of react-autocomplete

  • Limited additional input enhancement features compared to react-input-enhancements
  • May require more setup and configuration for advanced use cases
  • Less frequent updates and maintenance

Code Comparison

react-autocomplete:

<Autocomplete
  getItemValue={(item) => item.label}
  items={[
    { label: 'apple' },
    { label: 'banana' },
    { label: 'pear' }
  ]}
  renderItem={(item, isHighlighted) =>
    <div style={{ background: isHighlighted ? 'lightgray' : 'white' }}>
      {item.label}
    </div>
  }
  value={value}
  onChange={(e) => setValue(e.target.value)}
  onSelect={(val) => setValue(val)}
/>

react-input-enhancements:

<Autocomplete
  options={['apple', 'banana', 'pear']}
  value={value}
  onChange={setValue}
  getOptionLabel={(option) => option}
  renderInput={(params) => (
    <input {...params} placeholder="Choose a fruit" />
  )}
/>

Both libraries offer similar core functionality for autocomplete, but react-input-enhancements provides a more comprehensive set of input enhancements beyond just autocomplete. The code examples demonstrate the different approaches to implementation, with react-autocomplete offering more granular control over rendering and item handling, while react-input-enhancements provides a more streamlined API for basic use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

🏚

This project was originally thought to be an experiment and currently is unmaintained (and buggy)

Use it at your own risk

Also, consider using more modern, WAI-ARIA compliant approach like downshift

react-input-enhancements Gitter chat

Set of enhancements for input control

The intention of creating this library was to bring input component out of the dropdown/autocomplete/whatever code, so it could be easily replaced with your custom component, and also to split independent functionality into different components, which could be combined with each other (still not quite sure it was worth it, though).

There are currently five components:

  1. <Autosize />
  2. <Autocomplete />
  3. <Dropdown />
  4. <Mask />
  5. <DatePicker />

<Combobox /> is a combination of Dropdown, Autosize and/or Autocomplete components.

Demo

http://alexkuz.github.io/react-input-enhancements/

How it works

  • Each component is responsible for a corresponding behaviour (<Autosize> resizes <input> according to it's content length, <Dropdown> adds popup with options, and so on).
  • All components accept function as a child, providing props as a first argument, which you should pass to your input component. If there is nothing else except input, it could be passed as a child directly (for simplicity).
  • If you need to have combined behaviour in your component, let's say <Autosize> with <Autocomplete> just pass <Autocomplete> as a child to <Autosize> (see <Combobox> source code for reference)

Registering <input>

All components needs an access to <input> DOM element. To provide it, use getInputComponent prop:

let input;

getInput() {
  return input;
}

<Autocomplete
  options={options}
  getInputComponent={getInput}
>
  {props =>
    <input
      ref={c => input = c}
      {...props}
    />
  }
</Autocomplete>

Or, if you don't want to store the node in your component:

<Autocomplete
  options={options}
>
  {(props, otherProps, registerInput) =>
    <input
      ref={c => registerInput(c)}
      {...props}
    />
  }
</Autocomplete>

The first option also allows you to use shorter form with implicit parameters passing:

let input;

getInput() {
  return input;
}

<Autocomplete
  options={options}
  getInputComponent={getInput}
>
  <input
    ref={c => input = c}
  />
</Autocomplete>

However, this is not preferable as there is too much magic happening.

If <input> element wasn't provided, component tries to find node automatically, however this behaviour is deprecated and will be removed in future versions.

Autosize

Autosize resizes component to fit it's content.

<Autosize defaultValue={value}
          minWidth={100}>
  {(inputProps, { width, registerInput }) =>
    <input type='text' {...inputProps} ref={c => registerInput(c)} />
  }
</Autosize>

Autosize Props

  • value string - Input value (for a controlled component)
  • defaultValue string - Initial value (for a uncontrolled component)
  • getInputElement function() - Optional callback that provides <input> DOM element
  • registerInput function - Registers <input> DOM element
  • defaultWidth number - Minimum input width

Autocomplete

Autocomplete prompts a value based on provided options (see also react-autocomplete for the same behaviour)

<Autocomplete defaultValue={value}
              options={options}>
  {(inputProps, { matchingText, value, registerInput }) =>
    <input type='text' {...inputProps} ref={c => registerInput(c)} />
  }
</Autocomplete>

Autocomplete Props

  • value string - Input value (for a controlled component)
  • defaultValue string - Initial value (for a uncontrolled component)
  • getInputElement function - Optional callback that provides <input> DOM element
  • registerInput function - Registers <input> DOM element
  • options array - Array of options that are used to predict a value

options is an array of strings or objects with a text or value string properties.

Dropdown

Dropdown shows a dropdown with a (optionally filtered) list of suitable options.

<Dropdown defaultValue={value}
          options={options}>
  {(inputProps, { textValue }) =>
    <input type='text' {...inputProps} />
  }
</Dropdown>

Dropdown Props

  • value string - Input value (for a controlled component)
  • defaultValue string - Initial value (for a uncontrolled component)
  • options array - Array of shown options
  • onRenderOption function(className, style, option) - Renders option in list
  • onRenderCaret function(className, style, isActive, children) - Renders a caret
  • onRenderList function(className, style, isActive, listShown, children, header) - Renders list of options
  • onRenderListHeader function(allCount, shownCount, staticCount) - Renders list header
  • dropdownProps object - Custom props passed to dropdown root element
  • optionFilters array - List of option filters
  • getInputElement function - Optional callback that provides <input> DOM element
  • registerInput function - Registers <input> DOM element

options is an array of strings or objects with a shape:

  • value - "real" value of on option
  • text - text used as input value when option is selected
  • label - text or component rendered in list
  • static - option is never filtered out or sorted
  • disabled - option is not selectable

null option is rendered as a separator

optionFilters is an array of filters for options (for convenience). By default, these filters are used:

  • filters.filterByMatchingTextWithThreshold(20) - filters options by matching value, if options length is more than 20
  • filters.sortByMatchingText - sorting by matching value
  • filters.limitBy(100) - cuts options longer than 100
  • filters.notFoundMessage('No matches found') - shows option with 'No matches found' label if all options are filtered out
  • filters.filterRedudantSeparators - removes redudant separators (duplicated or at the begin/end of the list)

Mask

Mask formats input value.

<Mask defaultValue={value}
      pattern='0000-0000-0000-0000'>
  {(inputProps, { value }) =>
    <input type='text' {...inputProps} />
  }
</Mask>

Mask Props

  • value string - Input value (for a controlled component)
  • defaultValue string - Initial value (for a uncontrolled component)
  • getInputElement function - Optional callback that provides <input> DOM element
  • registerInput function - Registers <input> DOM element
  • pattern string - String formatting pattern. Only '0' (digit) or 'a' (letter) pattern chars are currently supported.
  • emptyChar string - Character used as an empty symbol (' ' by default)
  • placeholder string - If set, it is shown when unmaskedValue is empty
  • onUnmaskedValueChange function(text) - Fires when value is changed, providing unmasked value
  • onValuePreUpdate function - Optional callback to update value before it is parsed by Mask

DatePicker

DatePicker uses Mask to format date and shows calendar (react-date-picker by default) in popup.

<DatePicker defaultValue={moment(value).format('ddd DD/MM/YYYY')}
            placeholder={moment().format('ddd DD/MM/YYYY')}
            pattern='ddd DD/MM/YYYY'
            locale='en'>
  {(inputProps, { value }) =>
    <input type='text' {...inputProps} />
  }
</DatePicker>

DatePicker Props

  • value string - Input value (for a controlled component)
  • defaultValue string - Initial value (for a uncontrolled component)
  • pattern string - Date formatting pattern. For now, only these tokens are supported:
    • DD - day of month
    • MM - month
    • YYYY - year
    • ddd - day of week (not editable)
  • placeholder string - If set, it is shown when unmaskedValue is empty
  • locale string - Date locale
  • todayButtonText string - Text for 'Go to Today' button label
  • onRenderCalendar function({ styling, style, date, isActive, popupShown, onSelect, locale, todayButtonText }) - Returns calendar component shown in popup (react-day-picker-themeable by default)
  • onChange function(date) - Fires when date is selected, providing moment.js object
  • getInputElement function - Optional callback that provides <input> DOM element
  • registerInput function - Registers <input> DOM element
  • onValuePreUpdate function - Optional callback to update value before it is parsed by DatePicker. In this example, it parses inserted timestamp:
onValuePreUpdate={v => parseInt(v, 10) > 1e8 ?
  moment(parseInt(v, 10)).format('ddd DD/MM/YYYY') : v
}

Combobox

Combobox combines Dropdown, Autosize and/or Autocomplete components.

<Combobox defaultValue={value}
          options={options}
          autosize
          autocomplete>
  {(inputProps, { matchingText, width }) =>
    <input type='text' {...inputProps} />
  }
</Combobox>

Autosize and Autocomlete are enabled with corresponding bool props, other properties are proxied to Dropdown component.

See demo for code examples.

Some other (probably better) implementations

NPM DownloadsLast 30 Days