Giter Site home page Giter Site logo

agtlucas / react-kadabra Goto Github PK

View Code? Open in Web Editor NEW

This project forked from downshift-js/downshift

0.0 0.0 0.0 137 KB

๐Ÿ”ฎ Primitives to build simple, flexible, WAI-ARIA compliant React autocomplete/dropdown/select/combobox components

License: MIT License

JavaScript 100.00%

react-kadabra's Introduction

react-kadabra ๐Ÿ”ฎ

Primitives to build simple, flexible, WAI-ARIA compliant React autocomplete/dropdown/select/combobox components


Build Status Code Coverage version downloads MIT License

All Contributors PRs Welcome Code of Conduct

Watch on GitHub Star on GitHub Tweet

The problem

You need an autocomplete/dropdown/select experience in your application and you want it to be accessible. You also want it to be simple and flexible to account for your use cases.

This solution

This is a collection of primitive components that you can compose together to create an autocomplete component which you can reuse in your application. It's based on ideas from the talk "Compound Components" which effectively gives you maximum flexibility with a minimal API because you are responsible for the rendering of the autocomplete components.

This differs from other solutions which render things for their use case and then expose many options to allow for extensibility causing an API that is less easy to use and less flexible as well as making the implementation more complicated and harder to contribute to.

NOTE: The original use case of this component is autocomplete, however the API is powerful and flexible enough to build things like dropdowns as well.

Installation

This component is currently under development and is not yet released...

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save react-kadabra@beta

This package also depends on react and prop-types. Please make sure you have those installed as well.

Usage

Things are still in flux a little bit (looking for feedback).

import Autocomplete from 'react-kadabra'

function BasicAutocomplete({items, onChange}) {
  return (
    <Autocomplete onChange={onChange}>
      {({
        getInputProps,
        getItemProps,
        isOpen,
        value,
        selectedItem,
        highlightedIndex
      }) => (
        <div>
          <input {...getInputProps({placeholder: 'Favorite color ?'})} />
          {isOpen ? (
            <div style={{border: '1px solid #ccc'}}>
              {items
                .filter(
                  i =>
                    !value ||
                    i.toLowerCase().includes(value.toLowerCase()),
                )
                .map((value, index) => (
                  <div
                    {...getItemProps({value, index})}
                    key={value}
                    style: {
                      backgroundColor:
                        highlightedIndex === index ? 'gray' : 'white',
                      fontWeight: selectedItem === item ? 'bold' : 'normal',
                    }
                  >
                    {item}
                  </div>
                ))}
            </div>
          ) : null}
        </div>
      )}
    </Autocomplete>
  )
}

function App() {
  return (
    <BasicAutocomplete
      items={['apple', 'orange', 'carrot']}
      onChange={item => console.log(item)}
    />
  )
}

Available components and relevant props:

Autocomplete

This is the only component. It renders a div and forwards props. Wrap everything in this.

getValue

function(item: any) | defaults to an identity function (i => String(i))

Used to determine the value for the selected item.

defaultSelectedItem

any | defaults to null

Pass an item that should be selected by default.

defaultHighlightedIndex

number/null | defaults to null

This is the initial index to highlight when the autocomplete first opens.

getA11yStatusMessage

function({ resultCount, highlightedItem, getValue}) | default messages provided in English

This function is passed as props to a Status component nested within and allows you to create your own assertive ARIA statuses.

A default getA11yStatusMessage function is provided that will check resultCount and return "No results." or if there are results but no item is highlighted, "resultCount results are available, use up and down arrow keys to navigate." If an item is highlighted it will run getValue(highlightedItem) and display the value of the highlightedItem.

onChange

function(item: any) | required

Called when the user selects an item

children

function({}) | required

This is called with an object with the properties listed below:

property type description
getRootProps function({}) returns the props you should apply to the root element that you render. It can be optional. Read more below
getInputProps function({}) returns the props you should apply to the input element that you render. Read more below
getItemProps function({}) returns the props you should apply to any menu item elements you render. Read more below
getButtonProps function({}) returns the props you should apply to any menu toggle button element you render. Read more below
highlightedIndex number / null the currently highlighted item
setHighlightedIndex function(index: number) call to set a new highlighted index
value string / null the current value of the autocomplete
isOpen boolean the menu open state
toggleMenu function(state: boolean) toggle the menu open state (if state is not provided, then it will be set to the inverse of the current state)
openMenu function() opens the menu
closeMenu function() closes the menu
selectedItem any the currently selected item
clearSelection function() clears the selection
selectItem function(item: any) selects the given item
selectItemAtIndex function(index: number) selects the item at the given index
selectHighlightedItem function() selects the item that is currently highlighted

The functions below are used to apply props to the elements that you render. This gives you maximum flexibility to render what, when, and wherever you like. You call these on the element in question (for example: <input {...getInputProps()})). It's advisable to pass all your props to that function rather than applying them on the element yourself to avoid your props being overridden (or overriding the props returned). For example: getInputProps({onKeyUp(event) {console.log(event)}}).

getRootProps

Most of the time, you can just render a div yourself and Autocompletely will apply the props it needs to do its job (and you don't need to call this function). However, if you're rendering a composite component (custom component) as the root element, then you'll need to call getRootProps and apply that to your root element.

Required properties:

  • refKey: if you're rendering a composite component, that component will need to accept a prop which it forwards to the root DOM element. Commonly, folks call this innerRef. So you'd call: getRootProps({refKey: 'innerRef'}) and your composite component would forward like: <div ref={props.innerRef} />
getInputProps

This method should be applied to the input you render. It is recommended that you pass all props as an object to this method which will compose together any of the event handlers you need to apply to the input while preserving the ones that react-kadabra needs to apply to make the input behave.

There are no required properties for this method.

getItemProps

This method should be applied to any menu items you render. You pass it an object and that object must contain index (number) and value (anything) properties.

Required properties:

  • index: this is how react-kadabra keeps track of your item when updating the highlightedIndex as the user keys around.
  • value: this is the item data that will be selected when the user selects a particular item.
getButtonProps

Call this and apply the returned props to a button. It allows you to toggle the Menu component. You can definitely build something like this yourself (all of the available APIs are exposed to you), but this is nice because it will also apply all of the proper ARIA attributes. The aria-label prop is in English. You should probably override this yourself so you can provide translations:

<button {...getButtonProps({
  'aria-label': translateWithId(isOpen ? 'close.menu' : 'open.menu'),
})} />

Examples

Examples exist on codesandbox.io:

If you would like to add an example, follow these steps:

  1. Fork this codesandbox
  2. Update the code for your example (add some form of documentation to explain what it is)
  3. Update the title and description
  4. Add the tag: react-kadabra:example

Inspiration

I was heavily inspired by Ryan Florence and his talk entitled: "Compound Components". I also took a few ideas from the code in react-autocomplete and jQuery UI's Autocomplete.

You can watch me build the first iteration of react-kadabra on YouTube:

Other Solutions

You can implement these other solutions using react-kadabra, but if you'd prefer to use these out of the box solutions, then that's fine too:

Contributors

Thanks goes to these people (emoji key):


Kent C. Dodds

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ

Jack Moore

๐Ÿ’ก

Travis Arnold

๐Ÿ’ป ๐Ÿ“–

Jeremy Gayed

๐Ÿ’ก

Haroen Viaene

๐Ÿ’ก

monssef

๐Ÿ’ก

Federico Zivolo

๐Ÿ“–

Divyendu Singh

๐Ÿ’ก

Muhammad Salman

๐Ÿ’ป

Joรฃo Alberto

๐Ÿ’ป

Bernard Lin

๐Ÿ’ป ๐Ÿ“–

Geoff Davis

๐Ÿ’ก

Anup

๐Ÿ“–

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

react-kadabra's People

Contributors

souporserious avatar rezof avatar dashed avatar reznord avatar bernard-lin avatar geoffdavis92 avatar haroenv avatar jtmthf avatar tizmagik avatar mhd-sln avatar vutran avatar

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.