Skip to content

Instantly share code, notes, and snippets.

@raafacachoeira
Last active March 16, 2022 13:48
Show Gist options
  • Save raafacachoeira/22959c310abe3d8a050e2da43274083b to your computer and use it in GitHub Desktop.
Save raafacachoeira/22959c310abe3d8a050e2da43274083b to your computer and use it in GitHub Desktop.
Wrapper tags Select2 for React Funcion Component
import React, { SelectHTMLAttributes, useEffect, useRef, VFC } from 'react';
import clsx from 'clsx';
type Tag = { id: string; text: string; selected?: boolean };
type TagResponse = { id: string; text: string; newTag: boolean };
type CreateTagConfig = { _query: string; term: string };
type Props = {
data?: Tag[];
maximumInputLength?: number;
createTag?: (params: CreateTagConfig) => TagResponse;
multiple?: boolean;
tokenSeparators?: string[];
} & SelectHTMLAttributes<HTMLSelectElement>;
export const Tags: VFC<Props> = ({
data,
className,
maximumInputLength,
createTag,
multiple = true,
lang,
tokenSeparators = [',', ';'],
...rest
}) => {
const ref = useRef<HTMLSelectElement>(null);
const defaultCreateTag = (params: CreateTagConfig) => {
const term = params.term.trim();
if (term === '') return null;
if (maximumInputLength) if (term.length > maximumInputLength) return null;
return {
id: term,
text: term,
newTag: true,
};
};
useEffect(() => {
const current = ref.current;
if (!current) return;
//@ts-ignore
const $current = $(current);
$current.select2({
width: '100%',
maximumInputLength: maximumInputLength,
data: data,
multiple: multiple,
tags: true,
tokenSeparators: tokenSeparators,
createTag: createTag ?? defaultCreateTag,
language: lang,
});
return () => $current.select2('destroy');
}, []);
return <select className={clsx(className, 'select2')} ref={ref} {...rest} />;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment