@choc-ui/chakra-autocomplete

中文文档
6.2.2发布于 2026/02/08MITTypeScriptESM + CJS近 30 天下载 20.2万
原始使用文档
文档目录28 节
  1. Chakra V3 and V2 Support
  2. Known issues with Chakra V3
  3. Install
  4. Preview
  5. With Mouse
  6. With Keyboard
  7. Usage
  8. Basic Usage
  9. Creating Groups
  10. Accessing the internal state
  11. Custom Rendering
  12. Multi Select with Tags
  13. Creatable Items
  14. Loading State
  15. Integration with Form Libraries
  16. Autocomplete methods
  17. Codesandbox Link Here
  18. API Reference
  19. AutoComplete
  20. AutoCompleteTag
  21. AutoCompleteInput
  22. AutoCompleteList
  23. AutoCompleteGroup
  24. AutoCompleteItem
  25. AutoCompleteCreatable
  26. Contribute
  27. Sponsors ✨
  28. Contributors ✨


🏇
@choc-ui/chakra-autocomplete



npm package npm  downloads NPM

GitHub Repo stars

All Contributors


AutoComplete Component for the Chakra UI Library.

Chakra V3 and V2 Support

AutoComplete Version 6+ supports Chakra UI V3. If you are using Chakra UI V2, please continue to use the current choc-autocomplete v5.X documentation here. We will continue to try and support Chakra V2 but will eventually be removed once V3 becomes more widely adopted.

For help migrating from Chakra UI V2 to V3, please see their migration guide

The public API of the AutoComplete components have not changed with this migration.

Known issues with Chakra V3

There is only 1 known display issue with Chakra V3. When using the multiple prop, it is no longer possible to replicate the same styling to the Box wrapper as what the underlying Input is using. We are still looking into ways to resolve this, but neither the Chakra nor next-themes teams have published guidance on this yet.

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, Field } from "@chakra-ui/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">
      <Field.Root w="60">
        <Field.Label>Olympics Soccer Winner</Field.Label>
        <AutoComplete openOnFocus>
          <AutoCompleteInput variant="subtle" />
          <AutoCompleteList>
            {countries.map((country, cid) => (
              <AutoCompleteItem
                key={`option-${cid}`}
                value={country}
                textTransform="capitalize"
              >
                {country}
              </AutoCompleteItem>
            ))}
          </AutoCompleteList>
        </AutoComplete>
        <Field.HelperText>Who do you support.</Field.HelperText>
      </Field.Root>
    </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 React from "react";
import {
  AutoComplete,
  AutoCompleteGroup,
  AutoCompleteGroupTitle,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
} from "@choc-ui/chakra-autocomplete";
import { Stack, Text } from "@chakra-ui/react";

export default function App() {
  const continents = {
    africa: ["nigeria", "south africa"],
    asia: ["japan", "south korea"],
    europe: ["united kingdom", "russia"],
  };
  return (
    <Stack direction="column">
      <Text>Group </Text>
      <AutoComplete openOnFocus>
        <AutoCompleteInput placeholder="Search..." variant="subtle" />
        <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>
    </Stack>
  );
}
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,
  Field, 
  Icon
} 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";
import { InputGroup } from "./components/ui/input-group";

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

  return (
    <Flex pt="48" justify="center" align="center" w="full">
      <Field.Root w="60">
        <Field.Label>Olympics Soccer Winner</Field.Label>
        <AutoComplete openOnFocus>
          {({ isOpen }) => (
            <>
              <InputGroup 
                endElement={<Icon>{isOpen ? <FiChevronRight /> : <FiChevronDown />}</Icon>}
              >
                <AutoCompleteInput variant="subtle" placeholder="Search..." />
              </InputGroup>
              <AutoCompleteList>
                {countries.map((country, cid) => (
                  <AutoCompleteItem
                    key={`option-${cid}`}
                    value={country}
                    textTransform="capitalize"
                  >
                    {country}
                  </AutoCompleteItem>
                ))}
              </AutoCompleteList>
            </>
          )}
        </AutoComplete>
        <Field.HelperText>Who do you support.</Field.HelperText>
      </Field.Root>
    </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 React from "react";
import {
  AutoComplete,
  AutoCompleteGroup,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
} from "@choc-ui/chakra-autocomplete";
import { Stack, Text } from "@chakra-ui/react";
import { Avatar } from "./components/ui/avatar";

export default function App() {
  const europeans = [
    { name: "Dan Abramov", image: "https://bit.ly/dan-abramov" },
    { name: "Kent Dodds", image: "https://bit.ly/kent-c-dodds" },
    { name: "Ryan Florence", image: "https://bit.ly/ryan-florence" },
  ];
  const nigerians = [
    { name: "Segun Adebayo", image: "https://bit.ly/sage-adebayo" },
    { name: "Prosper Otemuyiwa", image: "https://bit.ly/prosper-baba" },
  ];
  return (
    <Stack direction="column">
      <Text>Custom Render </Text>
      <AutoComplete rollNavigation>
        <AutoCompleteInput variant="subtle" placeholder="Search..." />
        <AutoCompleteList>
          <AutoCompleteGroup title="Nigerians" showDivider>
            {nigerians.map((person, oid) => (
              <AutoCompleteItem
                key={`nigeria-${oid}`}
                value={person.name}
                textTransform="capitalize"
                align="center"
              >
                <Avatar size="sm" name={person.name} src={person.image} />
                <Text ml="4">{person.name}</Text>
              </AutoCompleteItem>
            ))}
          </AutoCompleteGroup>
          <AutoCompleteGroup title="Europeans" showDivider>
            {europeans.map((person, oid) => (
              <AutoCompleteItem
                key={`europe-${oid}`}
                value={person.name}
                textTransform="capitalize"
                align="center"
              >
                <Avatar size="sm" name={person.name} src={person.image} />
                <Text ml="4">{person.name}</Text>
              </AutoCompleteItem>
            ))}
          </AutoCompleteGroup>
        </AutoCompleteList>
      </AutoComplete>
    </Stack>
  );
}

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.

Important - With Chakra UI V3, it is no longer possible to replicate the same styling to the Box wrapper as what the underlying Input is using. We are still looking into ways to resolve this, but neither the Chakra nor next-themes teams have published guidance on this yet.

import React from "react";
import {
  AutoComplete,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
  AutoCompleteTag,
} from "@choc-ui/chakra-autocomplete";
import { Stack, Text } from "@chakra-ui/react";

export default function App() {
  const countries = [
    "nigeria",
    "japan",
    "india",
    "united states",
    "south korea",
  ];
  return (
    <Stack direction="column">
      <Text>Multi select with tags</Text>
      <AutoComplete openOnFocus multiple onChange={(vals) => console.log(vals)}>
        <AutoCompleteInput placeholder="Search..." variant="subtle">
          {({ 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>
    </Stack>
  );
}

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.

import React from "react";
import {
  AutoComplete,
  AutoCompleteCreatable,
  AutoCompleteInput,
  AutoCompleteItem,
  AutoCompleteList,
  AutoCompleteTag,
} from "@choc-ui/chakra-autocomplete";
import { Stack, Text } from "@chakra-ui/react";

export default function App() {
  const options = ["apple", "appoint", "zap", "cap", "japan"];
  return (
    <Stack direction="column">
      <Text>Creatable </Text>
      <AutoComplete multiple rollNavigation creatable>
        <AutoCompleteInput
          variant="subtle"
          placeholder="Search basic..."
          autoFocus
        >
          {({ tags }) =>
            tags.map((tag, tid) => (
              <AutoCompleteTag
                key={tid}
                label={tag.value}
                onRemove={tag.onRemove}
                disabled={tag.label === "japan"}
              />
            ))
          }
        </AutoCompleteInput>
        <AutoCompleteList>
          {options.map((option, oid) => (
            <AutoCompleteItem
              key={`option-${oid}`}
              value={option}
              textTransform="capitalize"
            >
              {option}
            </AutoCompleteItem>
          ))}
          <AutoCompleteCreatable />
        </AutoCompleteList>
      </AutoComplete>
    </Stack>
  );
}

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

Loading State

Need to pull data from API, but don't want your users to see a blank screen? You can enable the loading state by passing the isLoading prop to AutoComplete. By doing this, 2 other props will be enabled

  1. loadingIcon on AutoCompleteInput will display some sort of loading icon on the right side of the input. By default, a Spinner will be displayed, but you can pass in any custom element to be rendered

  2. loadingState on AutoCompleteList can display custom loading content when isLoading is true. All content will be rendered in the center of the list. By default, a Spinner will be displayed, but you can pass in any custom element to be rendered.

Best practice is to combine setTimeout and useEffect to create a debounce effect. This will prevent un-necessary API calls if your user types relatively quickly.

A working code demo can be found here

Integration with Form Libraries

It is relatively easy to integrate with form libaries such as React Hook Form, Formik, and others. Working examples can be found in the demos folder of this repo. See the Contributing section of this doc on how to clone and set it up for testing.

Does your favorite form library not have a working example? Submit a PR to get it added and help others using this library quickly get up and running.

Autocomplete methods

Assign a ref to the AutoComplete component and call the available methods with:

ref.current?.resetItems();
ref.current?.removeItem(itemValue);

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.

Prop Type Description Default
closeOnBlur boolean close suggestions when input is blurred true
closeOnSelect boolean close suggestions when a suggestions is selected true when multiple=false, false when multiple=true
creatable boolean Allow addition of arbitrary values not present in suggestions false
defaultIsOpen boolean Suggestions list is open by default false
prefocusFirstItem boolean Should prefocus first item intially, on query change, on open, and on filter out of current focused item true
defaultValues Array Used to predefine tags, or value for the autocomplete component. Just pass an array of the values ———
disableFilter boolean disables filtering when set to true false
emphasize boolean | SystemStyleObject Highlight matching characters in suggestions, you can pass the styles - false false
defaultEmptyStateProps FlexProps Props to pass into the `Flex` component when using the default empty state. Does not apply when you supply your own custom `emptyState` ———
emptyState
boolean | MaybeRenderProp<{ value: Item["value"] }>
render message when no suggestions match query true
filter
(query: string, optionValue: Item["value"], optionLabel: Item["label"]) =>
  boolean;
custom filter function ———
focusInputOnSelect boolean focus input after a suggestion is selected true
freeSolo boolean allow entering of any arbitrary values false
isReadOnly boolean Make the component read-only false
isLoading boolean Display loading animation on both the input and list elements false
isPortalled boolean Determines if the popover content should be rendered in a Portal. Set to false to render content in DOM hierarchy.

Useful when rendering inside of a Dialog
true
listAllValuesOnFocus boolean Show all suggestions when user focuses the input, while it's not empty. false
matchWidth boolean Chakra UI Popover.positioning.sameWidth property to match the popover content's width to the width of the container true
maxSelections number limit possible number of tag selections in multiple mode ———
maxSuggestions number limit number of suggestions in list ———
multiple boolean allow tags multi selection false
onChange
(value: string | Item["value"][], item: Item| Item[]) => void
function to run whenever autocomplete value(s) changes ———
onSelectOption
(params: {
    item: Item;
    selectMethod: "mouse" | "keyboard" | null;
    isNewInput: boolean;
  }) => boolean | void
method to call whenever a suggestion is selected ———
onOptionFocus
(params: {
    item: Item;
    focusMethod: "mouse" | "keyboard" | null;
    isNewInput: boolean;
  }) => boolean | void
method to call whenever a suggestion is focused ———
onReady
(props:{tags:ItemTag[]}) => void
method that exposes variables used in component ———
onTagRemoved
(removedTag: Item["value"],item: Item, tags: Item["value"][]) => void
method to call whenever a tag is removed ———
openOnFocus boolean open suggestions when input is focuses false
placement PlacementWithLogical where autocomplete list will display. Accepts any valid value from Popover component bottom
restoreOnBlurIfEmpty boolean if false, clearing the value of the input field will also clear the selected option true
rollNavigation boolean allow keyboard navigation to switch to alternate ends when one end is reached false
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 ———
submitKeys;
string[]
A list of KeyboardEvent: key values, except for the "Enter" key, that trigger the click event of the currently selected Item. ———
suggestWhenEmpty boolean show suggestions when input value is empty false
value any value of the component in the controlled state ---

AutoCompleteTag

Tags for multiple mode

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

Prop
Type Description Required Default
disabled
string
In the event that you need to lock certain tag so that they can't be removed in the interface, you can set the tags disabled. No
———
label
string
Label that is displayed on the tag Yes
———
onRemove
() => void
Method to remove the tag from selected values Yes
———

AutoCompleteInput

Input for AutoComplete value.

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

Prop
Type Description Required Default
children
type children = MaybeRenderProp<{
  tags: Item & { onRemove: () => void }[];
}>;

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

<AutoCompleteInput variant="subtle">
  {({ tags }) =>
    tags.map((tag, tid) => (
      <AutoCompleteTag key={tid} label={tag.label} onRemove={tag.onRemove} />
    ))
  }
</AutoCompleteInput>
No
———
ref
RefObject<HTMLInputElement>
provides a ref to the input element so the value can be referenced in additional contexts No
———
hidePlaceholder boolean hides the placeholder when children is not an empty array. intended usage for
<AutoComplete multiple creatable />
No
false
loadingIcon
React.ReactNode | JSX
Element that will be displayed when isLoading is true No Spinner from Chakra-UI

AutoCompleteList

Wrapper for AutoCompleteGroup and AutoCompleteItem

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

Prop
Type Description Required Default
loadingState React.ReactNode | JSX Content displayed in list while isLoading is true. Content will be centered No Spinner from Chakra-UI with an md size

AutoCompleteGroup

Wrapper for collections of AutoCompleteItems

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

Prop
Type Description Required Default
showDivider boolean If true, a divider is shown No false
dividerColor string Color for divider, if present No inherit

AutoCompleteItem

This Composes your suggestions

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

Prop
Type Description Required Default
getValue (value:any) => any A method used to determine the key that holds the value, when the value prop is an object no
val => val;
label string The label for the Option no
———
value string or Object The value of the Option yes
———
fixed
boolean
Make an item visible at all times, regardless of filtering or maxSuggestions No ———
_fixed SystemStyleObject Styles for fixed Itemm No
{
  fontWeight: 'extrabold',
}
value string The value of the Option yes
———
disabled
boolean
Make an item disabled, so it cannot be selected No ———
_disabled SystemStyleObject Styles for disabled Item(s) No
{
  fontWeight: 'extrabold',
}
_selected SystemStyleObject Styles for selected Item(s) No
{
  fontWeight: 'extrabold',
}
_focus SystemStyleObject Styles for focused Item No
{
  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
Type Description Required Default
children
type children = MaybeRenderProp<{ value: any }>;

ReactNode or callback that returns ReactNode e.g.

<AutoCompleteCreatable>
  {({ value }) => <span>Add {value} to List</span>}
</AutoCompleteCreatable>
No
———
alwaysDisplay
boolean;

When true, AutoCompleteCreatable is shown even when the AutoCompleteInput is empty

No
———

Contribute

  • Clone this repository
git clone https://github.com/anubra266/choc-autocomplete.git
  • Install all dependencies (with yarn)
yarn
  • Install package example dependencies (with yarn)
cd example
yarn

Start the package server, and the example server

# root directory
yarn start

# example directory with (cd example)
yarn dev

Sponsors ✨

Thanks goes to these wonderful people (emoji key):

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Maicon Carraro

💻

Sam Margalit

📖

gepd

💻 🐛

Spencer Kaiser

📖

jcdogo

💻

daliudzius

💻

Fabien BERNARD

💻

Riccardo Lorenzi

🐛

Mathis Federico

🐛

Kyle Slusser

💻🐛

Karl F. Sellergren

🐛🔧

Jedediah Benhod

🐛

Janusz Kacalak

🐛

Thomas Hickman

🐛

Christopher Regner

📖🐛

EinarSnorrason

💻🐛🔧

gbermudez1992

💻🐛🔧

ido213

💻🐛🔧

Bjørn Madsen

🐛

Randy Lebeau

🐛

Jayvee Bustarde

🐛🔧

Ihor Zinchenko

🐛🔧

Brian Walendzinski

🐛🔧

Lynx

🐛

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

版本与发布记录

@choc-ui/chakra-autocomplete 共发布 145 个版本,首次发布于 2021/05/17;过去 12 个月发布了 2 个版本。

版本发布日期距今
6.2.2latest2026/02/089 个月前
5.9.1v5-latest2025/11/1411 个月前
6.2.12025/10/261 年前
6.2.02025/09/151.1 年前
6.1.72025/09/131.2 年前
6.1.62025/09/071.2 年前

关于 @choc-ui/chakra-autocomplete 的常见问题

如何安装 @choc-ui/chakra-autocomplete?

在项目目录运行 npm install @choc-ui/chakra-autocomplete,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@chakra-ui/react(^3.2.2)、@emotion/react(^11.13.5)、react(>=18.2.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@choc-ui/chakra-autocomplete 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@choc-ui/chakra-autocomplete 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@choc-ui/chakra-autocomplete 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=10。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@choc-ui/chakra-autocomplete 可以商用吗?

@choc-ui/chakra-autocomplete 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@choc-ui/chakra-autocomplete 的下载量有多少?

根据 npm 官方下载统计,@choc-ui/chakra-autocomplete 在 2026/10/10 – 2026/11/08 这 30 天内被下载 201,726 次,日均约 6,724 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@choc-ui/chakra-autocomplete 还在维护吗?

最新版本 6.2.2 发布于 2026/02/08(9 个月前);至今共发布 145 个版本,其中过去 12 个月发布了 2 个;首次发布于 2021/05/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。