Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface TagsInputProps {
placeHolder?: string;
value?: string[];
onChange?: (tags: string[]) => void;
onBlur?: any;
onBlur?: React.FocusEventHandler<HTMLInputElement>;
separators?: string[];
disableBackspaceRemove?: boolean;
onExisting?: (tag: string) => void;
Expand Down Expand Up @@ -44,30 +44,31 @@ export const TagsInput = ({
onKeyUp,
classNames,
}: TagsInputProps) => {
const [tags, setTags] = useState<any>(value || []);
const [tags, setTags] = useState<string[]>(value || []);

useDidUpdateEffect(() => {
onChange && onChange(tags);
}, [tags]);

useDidUpdateEffect(() => {
if (JSON.stringify(value) !== JSON.stringify(tags)) {
if (value && JSON.stringify(value) !== JSON.stringify(tags)) {
setTags(value);
}
}, [value]);

const handleOnKeyUp = e => {
const handleOnKeyUp: React.KeyboardEventHandler<HTMLInputElement> = e => {
e.stopPropagation();

const text = e.target.value;
const target = e.target as HTMLInputElement;
const text = target.value;

if (
!text &&
!disableBackspaceRemove &&
tags.length &&
e.key === "Backspace"
) {
e.target.value = isEditOnRemove ? `${tags.at(-1)} ` : "";
target.value = isEditOnRemove ? `${tags.at(-1)} ` : "";
setTags([...tags.slice(0, -1)]);
}

Expand All @@ -80,11 +81,11 @@ export const TagsInput = ({
return;
}
setTags([...tags, text]);
e.target.value = "";
target.value = "";
}
};

const onTagRemove = text => {
const onTagRemove = (text: string) => {
setTags(tags.filter(tag => tag !== text));
onRemoved && onRemoved(text);
};
Expand Down
4 changes: 2 additions & 2 deletions src/tag.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import cc from "./classnames";

interface TagProps {
text: string;
remove: any;
remove: (tag: string) => void;
disabled?: boolean;
className?: string;
}

export default function Tag({ text, remove, disabled, className }: TagProps) {
const handleOnRemove = e => {
const handleOnRemove: React.MouseEventHandler<HTMLButtonElement> = e => {
e.stopPropagation();
remove(text);
};
Expand Down
7 changes: 5 additions & 2 deletions src/use-did-update-effect.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { useEffect, useRef } from "react";

export function useDidUpdateEffect(fn, inputs) {
export function useDidUpdateEffect(
fn: () => void,
inputs: ReadonlyArray<unknown>
) {
const didMountRef = useRef(false);

useEffect(() => {
if (didMountRef.current) fn();
else didMountRef.current = true;
}, inputs);
}
}