Package Exports
- react-custom-autocomplete
Readme
React Custom Autocomplete
React component for customizing user input autocomplete - using contenteditable div
A flexible and customizable React component that provides a content-editable <div> for user input, ideal for autocomplete and rich text scenarios.
Built using Rslib.
Installation
npm i react-custom-autocompleteUsage - Plaintext
import { AutocompleteContentEditable } from "react-content-editable-autocomplete";
const onSelectMenuItem = (item: Menu.Item) =>
console.log("Menu item selected:", item);
const onSearchFruits = (value: string) => {
// Simulate search results
return [
{ label: "Apple", value: "apple", icon: <span>🍎</span> },
{ label: "Banana", value: "banana", icon: <span>🍌</span> },
{ label: "Cherry", value: "cherry", icon: <span>🍒</span> },
// ...
].filter((item) => item.label.toLowerCase().includes(value.toLowerCase()));
};
<AutocompleteContentEditable
onSelectMenuItem={onSelectMenuItem}
placeholder='Search for fruits, start query with "/"'
searchTrigger='/'
style={{
width: "50vw",
background: "white",
}}
onSearch={onSearchFruits}
value=''
/>;Usage - Custom HTML Tag
In some cases, you want to apply special styling to the autocompleted terms, or a different HTML tag altogether (i.e. anchor <a> or button <button> tag), that's where using contenteditable div for the underlying textarea comes in handy, it allows for raw HTML (with developer-imposed restrictions in this case to prevent Cross-Site Scripting attack) to be rendered directly inside the textarea div.
Here's an example usage:
import { AutocompleteContentEditable } from "react-content-editable-autocomplete";
import { AutocompleteContentEditable as AutocompleteContentEditableType } from "react-content-editable-autocomplete/dist/types/AutocompleteContentEditable";
const tags = [
{ label: "#Lifestyle", value: "lifestyle" },
{ label: "#Technology", value: "technology" },
// ...
];
const onSearchTags = (value: string) => {
// Simulate search results
return value && value.length > 0
? tags.filter((item) =>
item.label.toLowerCase().includes(value.toLowerCase())
)
: tags;
};
const SelectionCustomization: AutocompleteContentEditableType.SelectionHTMLTag<"i"> =
{
HTMLTag: "i",
HTMLInlineStyle: {
padding: "5px 10px",
fontSize: "12px",
backgroundColor: "#e3edf9",
borderRadius: "16px",
color: "#4d80c5",
},
HTMLClassName: "custom-tag-class",
};
<AutocompleteContentEditable
onSelectMenuItem={onSelectMenuItem}
placeholder='Search for tags, start query with "#"'
searchTrigger='#'
// renderMenuItem={TagMenuItemCustomRendering}
style={{
width: "60vw",
background: "white",
}}
showSelectionAsHTMLTag={SelectionCustomization}
onSearch={onSearchTags}
value=''
/>;Local Dev Setup
Install the dependencies:
pnpm installGet started
Build the library:
pnpm buildBuild the library in watch mode:
pnpm dev