Skip to content

Wildhoney/ReactAutolist

Repository files navigation

ReactAutolist

Browser native implementation of autocomplete using the datalist element.

Travis   npm   License MIT   Coveralls   code style: prettier

npm: npm install react-autolist

yarn: yarn add react-autolist


Getting Started

Autolist uses the browser native <datalist /> tag for its auto-completion functionality.

import Autolist from 'react-autolist';

export default function App() {
    const handleSuggest = async (value) => {
        const list = await fetch(`/list/${value}`);
        return list.map((item) => ({ id: item.id, value: item.name }));
    };

    const handleChange = (suggestion) => {
        console.log(`You chose ${suggestion.value}!`);
    };

    return <Autolist onSuggest={handleSuggest} onChange={handleChange} />;
}

Adding the onSuggest callback allows you to initiate the search when the user types into the input field – and onChange is invoked when the user submits an item that is in the list of suggestions.

By default onSuggest is invoked for every character that's typed into the field no matter how small, however you can modify the behaviour by passing a minLength prop that will prevent the invocation if the text length is below the desired length.

You may also pass a children function that accepts the handleSubmit prop which can be invoked at any point, such as on the click of a button.

<Autolist onSuggest={handleSuggest} onChange={handleChange}>
    {(handleSubmit) => <button onClick={handleSubmit}>Submit!</button>}
</Autolist>

About

Browser native implementation of autocomplete using the datalist element.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published