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

chakra-autocomplete

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

chakra-autocomplete

```bash npm i --save @choc-ui/chakra-autocomplete #or yarn add @choc-ui/chakra-autocomplete ```

  • 4.0.0
  • unpublished
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source


🏇
@choc-ui/chakra-autocomplete



npm package npm  downloads NPM

GitHub Repo stars

All Contributors


AutoComplete Component for the Chakra UI Library.




npm i @choc-ui/chakra-autocomplete





Install

npm i --save @choc-ui/chakra-autocomplete
#or
yarn add @choc-ui/chakra-autocomplete

Preview

With Mouse

With Keyboard

Usage

Basic Usage

import { Flex, FormControl, FormHelperText, FormLabel } from "@chakra-ui/react";
import * as React from "react";
import {
  AutoComplete,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
} from "@choc-ui/chakra-autocomplete";

function App() {
  const countries = [
    "nigeria",
    "japan",
    "india",
    "united states",
    "south korea",
  ];

  return (
    <Flex pt="48" justify="center" align="center" w="full">
      <FormControl w="60">
        <FormLabel>Olympics Soccer Winner</FormLabel>
        <AutoComplete openOnFocus>
          <AutoCompleteInput variant="filled" />
          <AutoCompleteList>
            {countries.map((country, cid) => (
              <AutoCompleteItem
                key={`option-${cid}`}
                value={country}
                textTransform="capitalize"
              >
                {country}
              </AutoCompleteItem>
            ))}
          </AutoCompleteList>
        </AutoComplete>
        <FormHelperText>Who do you support.</FormHelperText>
      </FormControl>
    </Flex>
  );
}

export default App;
CleanShot 2021-07-28 at 23 47 57@2x

Creating Groups

You can create groups with the AutoCompleteGroup Component, and add a title with the AutoCompleteGroupTitle component.

import { Flex, FormControl, FormHelperText, FormLabel } from "@chakra-ui/react";
import * as React from "react";
import {
  AutoComplete,
  AutoCompleteGroup,
  AutoCompleteGroupTitle,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
} from "@choc-ui/chakra-autocomplete";

function App() {
  const continents = {
    africa: ["nigeria", "south africa"],
    asia: ["japan", "south korea"],
    europe: ["united kingdom", "russia"],
  };

  return (
    <Flex pt="48" justify="center" align="center" w="full">
      <FormControl w="60">
        <FormLabel>Olympics Soccer Winner</FormLabel>
        <AutoComplete openOnFocus>
          <AutoCompleteInput variant="filled" />
          <AutoCompleteList>
            {Object.entries(continents).map(([continent, countries], co_id) => (
              <AutoCompleteGroup key={co_id} showDivider>
                <AutoCompleteGroupTitle textTransform="capitalize">
                  {continent}
                </AutoCompleteGroupTitle>
                {countries.map((country, c_id) => (
                  <AutoCompleteItem
                    key={c_id}
                    value={country}
                    textTransform="capitalize"
                  >
                    {country}
                  </AutoCompleteItem>
                ))}
              </AutoCompleteGroup>
            ))}
          </AutoCompleteList>
        </AutoComplete>
        <FormHelperText>Who do you support.</FormHelperText>
      </FormControl>
    </Flex>
  );
}

export default App;
CleanShot 2021-07-29 at 01 18 47@2x

Accessing the internal state

To access the internal state of the AutoComplete, use a function as children (commonly known as a render prop). You'll get access to the internal state isOpen, with the onOpen and onClose methods.

import {
  Flex,
  FormControl,
  FormHelperText,
  FormLabel,
  Icon,
  InputGroup,
  InputRightElement,
} from "@chakra-ui/react";
import * as React from "react";
import {
  AutoComplete,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
} from "@choc-ui/chakra-autocomplete";
import { FiChevronRight, FiChevronDown } from "react-icons/fi";

function App() {
  const countries = [
    "nigeria",
    "japan",
    "india",
    "united states",
    "south korea",
  ];

  return (
    <Flex pt="48" justify="center" align="center" w="full">
      <FormControl w="60">
        <FormLabel>Olympics Soccer Winner</FormLabel>
        <AutoComplete openOnFocus>
          {({ isOpen }) => (
            <>
              <InputGroup>
                <AutoCompleteInput variant="filled" placeholder="Search..." />
                <InputRightElement
                  children={
                    <Icon as={isOpen ? FiChevronRight : FiChevronDown} />
                  }
                />
              </InputGroup>
              <AutoCompleteList>
                {countries.map((country, cid) => (
                  <AutoCompleteItem
                    key={`option-${cid}`}
                    value={country}
                    textTransform="capitalize"
                  >
                    {country}
                  </AutoCompleteItem>
                ))}
              </AutoCompleteList>
            </>
          )}
        </AutoComplete>
        <FormHelperText>Who do you support.</FormHelperText>
      </FormControl>
    </Flex>
  );
}

export default App;
CleanShot 2021-07-29 at 01 29 46@2x

Custom Rendering

You can Render whatever you want. The AutoComplete Items are regular Chakra Boxes.

import {
  Avatar,
  Flex,
  FormControl,
  FormHelperText,
  FormLabel,
  Text,
} from "@chakra-ui/react";
import * as React from "react";
import {
  AutoComplete,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
} from "@choc-ui/chakra-autocomplete";

function App() {
  const people = [
    { name: "Dan Abramov", image: "https://bit.ly/dan-abramov" },
    { name: "Kent Dodds", image: "https://bit.ly/kent-c-dodds" },
    { name: "Segun Adebayo", image: "https://bit.ly/sage-adebayo" },
    { name: "Prosper Otemuyiwa", image: "https://bit.ly/prosper-baba" },
    { name: "Ryan Florence", image: "https://bit.ly/ryan-florence" },
  ];

  return (
    <Flex pt="48" justify="center" align="center" w="full" direction="column">
      <FormControl id="email" w="60">
        <FormLabel>Olympics Soccer Winner</FormLabel>
        <AutoComplete openOnFocus>
          <AutoCompleteInput variant="filled" />
          <AutoCompleteList>
            {people.map((person, oid) => (
              <AutoCompleteItem
                key={`option-${oid}`}
                value={person.name}
                textTransform="capitalize"
                align="center"
              >
                <Avatar size="sm" name={person.name} src={person.image} />
                <Text ml="4">{person.name}</Text>
              </AutoCompleteItem>
            ))}
          </AutoCompleteList>
        </AutoComplete>
        <FormHelperText>Who do you support.</FormHelperText>
      </FormControl>
    </Flex>
  );
}

export default App;
CleanShot 2021-07-29 at 01 35 03@2x

Multi Select with Tags

Add the multiple prop to AutoComplete component, the AutoCompleteInput will now expose the tags in it's children function. The onChange prop now returns an array of the chosen values

Now you can map the tags with the AutoCompleteTag component or any other component of your choice. The label and the onRemove method are now exposed.

import { Flex, FormControl, FormHelperText, FormLabel } from "@chakra-ui/react";
import * as React from "react";
import {
  AutoComplete,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
  AutoCompleteTag,
} from "@choc-ui/chakra-autocomplete";

function App() {
  const countries = [
    "nigeria",
    "japan",
    "india",
    "united states",
    "south korea",
  ];

  return (
    <Flex pt="48" justify="center" align="center" w="full" direction="column">
      <FormControl id="email" w="60">
        <FormLabel>Olympics Soccer Winner</FormLabel>
        <AutoComplete openOnFocus multiple onChange={vals => console.log(vals)}>
          <AutoCompleteInput variant="filled">
            {({ tags }) =>
              tags.map((tag, tid) => (
                <AutoCompleteTag
                  key={tid}
                  label={tag.label}
                  onRemove={tag.onRemove}
                />
              ))
            }
          </AutoCompleteInput>
          <AutoCompleteList>
            {countries.map((country, cid) => (
              <AutoCompleteItem
                key={`option-${cid}`}
                value={country}
                textTransform="capitalize"
                _selected={{ bg: "whiteAlpha.50" }}
                _focus={{ bg: "whiteAlpha.100" }}
              >
                {country}
              </AutoCompleteItem>
            ))}
          </AutoCompleteList>
        </AutoComplete>
        <FormHelperText>Who do you support.</FormHelperText>
      </FormControl>
    </Flex>
  );
}

export default App;

Kapture 2021-07-29 at 02 05 53

Creatable Items

I know that title hardly expresses the point, but yeah, naming is tough. You might want your users to be able to add extra items when their options are not available in the provided options. e.g. adding a new tag to your Polywork profile.

First add the creatable prop to the AutoComplete component. Then add the AutoCompleteCreatable component to the bottom of the list. Refer to the references for more info on this component.

CleanShot 2021-07-29 at 02 29 20@2x

API Reference

NB: Feel free to request any additional Prop in Issues.

AutoComplete

Wrapper and Provider for AutoCompleteInput and AutoCompleteList

AutoComplete composes Box so you can pass all Box props to change its style.

NB: None of the props passed to it are required.

export type UseAutoCompleteProps = Partial<{
  closeOnBlur: boolean; //close suggestions when input is blurred - true
  closeOnSelect: boolean; //close suggestions when a suggestions is selected - true
  creatable: boolean; //Allow addition of arbitrary values not present in suggestions - false
  defaultIsOpen: boolean; //Suggestions list is open by default -- false
  emphasize: boolean | CSSObject; //Highlight matching characters in suggestions, you can pass the styles - false
  emptyState: boolean | MaybeRenderProp<{ value: Item["value"] }>; //render message when no suggestions match query
  filter: (query: string, itemValue: Item["value"]) => boolean; //custom filter function
  focusInputOnSelect: boolean; //focus input after a suggestion is selected - true
  freeSolo: boolean; //allow entering of any values
  maxSuggestions: number; //limit number of suggestions in list
  multiple: boolean; //allow tags multi selection - false
  onChange: (value: string | Item["value"][]) => void; //function to run whenever autocomplete value(s) changes
  onSelectOption: (params: {
    optionValue: string;
    selectMethod: "mouse" | "keyboard" | null;
    isNewInput: boolean;
  }) => boolean | void; //method to call whenever a suggestion is selected
  onOptionFocus: (params: {
    optionValue: string;
    selectMethod: "mouse" | "keyboard" | null;
    isNewInput: boolean;
  }) => boolean | void;//method to call whenever a suggestion is focused
  onTagRemoved: (removedTag: Item["value"], tags: Item["value"][]) => void; //method to call whenever a tag is removed
  openOnFocus: boolean; //open suggestions when input is focuses -false
  rollNavigation: boolean; //allow keyboard navigation to switch to alternate ends when one end is reached
  selectOnFocus: boolean; //select the text in input when it's focused. - false
  shouldRenderSuggestions: (value: string) => boolean; //function to decide if suggestions should render, e.g. show suggestions only if there are at least two characters in the query value
  suggestWhenEmpty: boolean; //show suggestions when input value is empty - false
}>;
}

AutoCompleteTag

Tags for multiple mode

AutoCompleteTag composes Tag so you can pass all Tag props to change its style.

Prop
TypeDescriptionRequiredDefault
label
string
Label that is displayed on the tagYes
———
onRemove
() => void
Method to remove the tag from selected valuesYes
———

AutoCompleteInput

Input for AutoComplete value.

AutoCompleteInput composes Input so you can pass all Input props to change its style.

Prop
TypeDescriptionRequiredDefault
children
type children = MaybeRenderProp<{
  tags: { label: string; onRemove: () => void }[];
}>;

callback that returns ReactNode and is provided with tags in multiple mode e.g.

<AutoCompleteInput variant="filled">
  {({ tags }) =>
    tags.map((tag, tid) => (
      <AutoCompleteTag key={tid} label={tag.label} onRemove={tag.onRemove} />
    ))
  }
</AutoCompleteInput>
No
———

AutoCompleteList

Wrapper for AutoCompleteGroup and AutoCompleteItem

AutoCompleteList composes Box so you can pass all Box props to change its style.

AutoCompleteGroup

Wrapper for collections of AutoCompleteItems

AutoCompleteGroup composes Box so you can pass all Box props to change its style.

Prop
TypeDescriptionRequiredDefault
showDividerbooleanIf true, a divider is shownNofalse
dividerColorstringColor for divider, if presentNoinherit
### **AutoCompleteItem**

This Composes your suggestions

AutoCompleteItem composes Flex so you can pass all Flex props to change its style.

Prop
TypeDescriptionRequiredDefault
valuestringThe value of the Optionyes
———
fixed
boolean
Make an item visible at all times, regardless of filteringNo———
_fixed
CSSObject
Styles for fixed ItemmNo
{
  fontWeight: 'extrabold',
}
valuestringThe value of the Optionyes
———
disabled
boolean
Make an item disabled, so it cannot be selectedNo———
_disabled
CSSObject
Styles for disabled Item(s)No
{
  fontWeight: 'extrabold',
}
_selected
CSSObject
Styles for selected Item(s)No
{
  fontWeight: 'extrabold',
}
_focus
CSSObject
Styles for focused ItemNo
{
  fontWeight: 'extrabold',
}

AutoCompleteCreatable

Used with the AutoComplete component's creatable prop, to allow users enter arbitrary values, not available in the provided options.

AutoCompleteCreatable composes Flex so you can pass all Flex props to change its style.

It also accepts a function as its children prop which is provided with the current inputValue.

Prop
TypeDescriptionRequiredDefault
children
type children = MaybeRenderProp<{ value: any }>;

ReactNode or callback that returns ReactNode e.g.

<AutoCompleteCreatable>
  {({ value }) => <span>Add {value} to List</span>}
</AutoCompleteCreatable>
No
———
## Contributors ✨

Thanks goes to these wonderful people (emoji key):


Abraham

💻

Sam Margalit

📖

gepd

💻

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

FAQs

Package last updated on 29 Jul 2021

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