Skip to content

TokenInput ​

A row of removable tokens followed by free text, such as the recipients of a message or the tags of a note. You hold both the tokens and the text.

tsx
import { TokenInput } from '@adecore/ui';
tsx
import { TokenInput, type TokenInputToken } from '@adecore/ui';
import { useState } from 'react';

const ADDRESS = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

export default function TokenInputDemo() {
    const [recipients, setRecipients] = useState<TokenInputToken[]>([
        { key: 'sanne@example.com', label: 'Sanne de Vries' },
        { key: 'jan@example.com', label: 'Jan Dekker' }
    ]);
    const [text, setText] = useState('');

    const add = (value: string): void => {
        const address = value.trim();

        setRecipients((current) =>
            current.some((token) => token.key === address) ? current : [...current, { key: address, label: address, invalid: !ADDRESS.test(address) }]
        );
        setText('');
    };

    return (
        <div className="w-96">
            <TokenInput
                label="To"
                placeholder="Name or address"
                tokens={recipients}
                value={text}
                onValueChange={setText}
                onCommit={add}
                onRemove={(key) => setRecipients((current) => current.filter((token) => token.key !== key))}
            />
        </div>
    );
}

Enter, a comma and a semicolon call onCommit with the text, and so does leaving the field. You decide what the text becomes, so the same field takes addresses and tags: parse it, add tokens and clear value. Empty text commits nothing.

Backspace in an empty field calls onRemove with the key of the last token. Each token has a remove button that does the same for its own token; removeLabel names it, or it reads "Remove" and the token's label.

invalid on the field marks the text; invalid on a token marks that token, such as an address that did not parse. variant="bare" drops the border, ground and focus outline, for a field inside a row that draws them, as with Input.

Inside a Field the text field takes its id, aria-describedby and aria-invalid from it. Outside one, give it a label.

Props ​

PropTypeDefault
tokensreadonly TokenInputToken[]Required. { key, label, invalid? }
valuestringRequired. The text after the last token.
onValueChange(value: string) => voidRequired.
onCommit(value: string) => voidRequired.
onRemove(key: string) => voidRequired.
labelstringThe accessible name of the text field.
removeLabel(token: TokenInputToken) => string
invalidbooleanfalse
variant'field' | 'bare''field'

The other props of an <input> go to the text field, className to the row. TokenInputProps and TokenInputToken are exported types.

Licenses and third-party notices are listed in each package.