Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

Textarea

A box for a longer answer, such as describing a situation or giving a reason. With a count, a pasted text is never cut: the box says how many characters are left or over, and the user shortens the text.

Package
@kvirn-ui/react
Testing
Automated. Core 0 of 2, Release 0 of 3

When to use it#

  • Use a Textarea when the answer is a few sentences or more: a description, a reason, a message to a case worker.
  • Put it in a Field with a visible label. Say what to answer in a description above the box, and a format or a limit in a help text under it.
  • Add a count only when the user can plausibly reach a limit, and only when your form has one. Don’t cut the text: let the user shorten it.
  • Not for a short answer such as a name or a phone number: use a TextInput. Not for an amount or a quantity: use a NumberInput.

Example#

Tell us what has happened and what you need help with.

Use cases#

A limit the user can see

Your form accepts at most 200 characters. The count says so before the user starts, says how many are left while they type, and says how many are over if they go past it. With characterCount the limit is not written as the native maxlength, so a pasted text is kept whole. Over the limit is a warning, never an error: your form decides on submit. A screen reader says the count politely when typing pauses (see Announcements).

Tell us what has happened and what you need help with.

You can enter up to 200 characters.

Props in this example:

Warning: Don't forget

Wrap your app in KvirnProvider. Without it the count still shows, but nothing is said aloud while the user types (4.1.3 Status Messages).

Count the way your server counts

The count and your server must agree, or a text the box accepts is refused on submit. Pass a function that counts the way the server does. By default the count counts what the user sees, and a line break is one character.

You can enter up to 200 characters.

Our case system counts a line break as two characters, and so does the count.

Props in this example:

An error after submit

KvirnUI validates nothing. Your form checks the text when it is sent, sets invalid on the Field and writes the message. Then move focus to the box, after the error has rendered, so the screen reader reads it with the box.

You can enter up to 200 characters.

Props in this example:

Warning: Don't forget

Say which field is wrong and how to fix it, in text: “Remove some text”, not just a red edge. See What you need to do.

A text that comes from your code

A saved draft, or a form your library resets. Pass value so the count follows it: an uncontrolled box counts what is typed, and does not see a text you write to the element later. A text set from code changes the count and says nothing aloud.

You can enter up to 200 characters.

Props in this example:

Information: Did you know?

A long answer is the worst thing to lose. Warn before a session ends, for example with an AlertDialog (2.2.1 Timing Adjustable), and save drafts in staff tools.

A count under a short text

CharacterCount is its own part, so another control can have a count. Put it directly after the control in the same Field, and the Field lists it in the control’s aria-describedby.

You can enter up to 80 characters.

One sentence, for the case list.

Props in this example:

Accessibility#

What it does for you#

  • APG pattern: none needed. Textarea is a native <textarea>. There is no APG pattern for a text field: the name, description and state come from HTML and aria-describedby.
  • Deviations: none from APG. With characterCount, maxLength is the count's limit and is not written as the native maxlength: the browser cuts a pasted text without a word, so someone who pastes a text from a draft loses part of it and is not told. The user sees how many characters are over and shortens the text. It is a documented choice of this library.
  • Native elements used: <textarea>. CharacterCount is a <p> (a help text). Neither adds a role.

Textarea is the multi-line text control of a Field (see the Field page). It is a native element: the browser supplies the role (textbox, multi-line), the keyboard, selection, spellcheck, paste, undo and autofill. Textarea adds the Field's wiring, the part class, rows (5 unless you set it) and, with characterCount, a count under the box. The count's part is CharacterCount, which the rich text editor also uses.

PartElement / roleARIA / stateNotes
Textarea<textarea> → textbox (multi-line)From the nearest Field: id, aria-describedby (descriptions, the count, help texts, then the error, in DOM order), aria-invalid="true", aria-required="true", native disabled, data-invalid, data-required, data-disabledClass kv-textarea. rows is 5 unless set. Your own aria-describedby ids are kept, after the Field's. data-focused while it has focus, and data-focus-visible only while that focus came from the keyboard. data-over while the count is over the limit. Native required, readOnly, disabled, autoComplete and spellCheck pass through. No aria-multiline: a <textarea> already is
no Field (or only a Fieldset)none added. With characterCount, aria-describedby points at the countNeeds aria-label or aria-labelledby, or a <label>. Dev warning (4.1.2, 3.3.2)
CharacterCount<p> (a help text), no role, not a live regionIn a Field: the description id the Field lists in the control's aria-describedby. Outside one (also directly in a Fieldset, which is not the box's host): its own id, which the Textarea adds and lists in the box's aria-describedby, and the count never registers with the Fieldset. This holds for the public CharacterCount too: it registers with a Field only, so directly in a Fieldset it keeps the id you give it (list it in your control's aria-describedby). data-over over the limit, data-near from the thresholdClasses kv-field-help-text kv-character-count. Directly after the control, so the DOM order is the reading order. The warning icon shows only over the limit and is decorative (aria-hidden): the words carry the state

The count (`characterCount`)#

With maxLength and characterCount, Textarea renders a CharacterCount right after the box. useTextarea with CharacterCount serves your own markup.

  • Limit: maxLength is the limit and is not written as the native attribute. A paste of any length is kept whole. Without characterCount, maxLength passes through as the native attribute.
  • Text: while empty, characterCount.limit ("You can enter up to 500 characters."). While typing, characterCount.remaining ("You have 120 characters remaining."). Over the limit, characterCount.over ("You have 12 characters too many.") with the warning icon and weight 600, never danger: before submit it is not an error.
  • Counting: characters as the user sees them (grapheme clusters, Intl.Segmenter), so a letter typed as a base letter plus a combining accent, or an emoji, counts as one, and a line break counts as one. countCharacters={(value) => number} replaces it when the server counts differently: count the same way on both sides.
  • Over the limit is a warning: nothing blocks typing or paste, and nothing is marked aria-invalid. The form decides on submit and writes a Field.ErrorMessage that names the fix. data-over is on the count and on the Textarea.
  • onValueChange(value, details) gets details.length, details.limit and details.isOverLimit with characterCount.
  • No limit, no count: characterCount without maxLength warns once in development and renders nothing.

What you need to do#

  • Put every Textarea in a Field with a Field.Label, or give it aria-label or aria-labelledby from your translations (4.1.2 Name, Role, Value, A).
  • Never use the placeholder as the label (3.3.2 Labels or Instructions, A). Put an example in the help text or the description, not in the box.
  • Set autoComplete where a token exists for the question (1.3.5 Identify Input Purpose, AA), and never block paste.
  • Raise the limit before you add a count: a count is for a limit the user can plausibly hit. Say the limit in the description or label only if the count is off, and never as the only place it appears.
  • Count the same way on both sides: pass countCharacters with the server's rule when it differs from what the user sees. Over the limit is a warning in the UI, so validate on submit and write a Field.ErrorMessage that names the field and the fix ("The description can be at most 500 characters. Remove 12 characters.").
  • With characterCount, pass value when you set the text from code (a draft restored, a form reset by your library): an uncontrolled box counts what is typed, follows a native form reset and reads the value the browser restored on load and on pageshow, but not a value you write to the element directly later.
  • In your own markup, outside a Field, pass CharacterCount an id and list it in your control's aria-describedby: nothing else links it to the box (1.3.1 Info and Relationships, A; 4.1.2 Name, Role, Value, A).
  • A long answer is the worst thing to lose: warn before a session timeout (2.2.1 Timing Adjustable, A) and, for staff tools, save drafts.
  • Read-only is for staff tools. In a resident form, avoid both read-only and disabled.
  • Wrap the app in KvirnProvider so the count is announced (4.1.3 Status Messages, AA).
  • Don't pass an id inside a Field: the Field's id wins (dev warning). Use <Field.Root controlId>.

Warning: Don't forget

Give every box a visible label in a Field. A placeholder is not a label: it disappears when the user types (3.3.2 Labels or Instructions). Without a name a screen reader says only that there is a text box (4.1.2 Name, Role, Value).

Visual and modes#

  • Focus indicator: on keyboard focus, a ring at least 2px thick, set off from the box, with at least 3:1 contrast against the adjacent colours (2.4.7 Focus Visible, AA; 2.4.13 Focus Appearance, AAA). A click shows a thicker edge in the focus colour and no ring. An invalid box keeps its thick error edge when it has focus, and the ring shows on any focus, a click included.
  • Target size: far above 24 × 24 CSS px (2.5.8 Target Size (Minimum), AA).
  • Boundary: the edge has at least 3:1 contrast against every surface the default theme uses, checked by its contrast check (1.4.11 Non-text Contrast, AA). Invalid: a thicker edge in the error colour, without moving the text. Disabled: a dashed edge, and the box cannot be resized. Read-only: a solid edge on a tinted surface, still focusable and resizable.
  • Size: the height is rows (5 by default). Where the browser supports field-sizing: content and typed attr(), the box grows with its text and rows is its minimum. No fixed height, so the extra room that 1.4.12 Text Spacing (AA) allows fits. Resize is vertical only: never wider than the field (1.4.10 Reflow, AA).
  • The count has the look of a help text, in every state. Over the limit it adds a bolder weight and the warning icon, never colour alone (1.4.1 Use of Color, A).
  • forced-colors behaviour (Windows contrast themes): the same system colours as TextInput. The box keeps a real border, an invalid box has a thicker border in the system text colour, and a disabled one a dashed border in the disabled-text colour. Keyboard focus draws a highlight ring. The count uses the system text colour: over the limit, the icon's shape and the weight carry it.
  • reduced-motion behaviour: colour transitions only when the user allows motion. The box never animates its height.
  • Reflow: full width and never wider than its container, long words wrap, no horizontal scrolling at 320 CSS px (1.4.10 Reflow, AA).
  • RTL: logical properties only. The caret keys are the browser's.

Warning: Don't forget

If you restyle the box, keep its edge at 3:1 contrast against the surface (1.4.11 Non-text Contrast) and a visible focus ring (2.4.7 Focus Visible). Show a text over the limit by more than colour, as the weight and icon do here (1.4.1 Use of Color).

Focus management#

  • Initial focus: not moved. No autoFocus by default.
  • Trap: no. Tab leaves the box: it is never a keyboard trap (2.1.2 No Keyboard Trap, A).
  • Restore to: not applicable.
  • Never obscured by: Textarea renders no overlay. If your page has a sticky header, add scroll-padding so it never covers the focused box (2.4.11 Focus Not Obscured (Minimum), AA).

Warning: Don't forget

If your page has a header that stays at the top while scrolling, add scroll-padding so it never covers the focused box (2.4.11 Focus Not Obscured (Minimum)).

WCAG success criteria#

  • 1.3.1 Info and Relationships (A): the label, description, count and error are programmatically associated (textarea.test.tsx › the description lists the description, the help text and the error, in DOM order). Directly in a Fieldset the count describes the box and not the fieldset (textarea.test.tsx › directly in a Fieldset, the count describes the box and not the fieldset, and for your own markup character-count.test.tsx › directly in a Fieldset, a count keeps its own id and describes the box, not the fieldset).
  • 1.3.5 Identify Input Purpose (AA): autoComplete passes through (textarea.test.tsx › forwards its ref and native props, and the part class kv-textarea joins a consumer’s).
  • 1.4.1 Use of Color (A), 1.4.3 Contrast (Minimum) (AA), 1.4.11 Non-text Contrast (AA): the invalid edge and message, text contrast and edge contrast.
  • 1.4.10 Reflow (AA): the box is never wider than its container (textarea.stories.tsx › Widths).
  • 2.1.1 Keyboard (A) and 2.1.2 No Keyboard Trap (A): native, and Tab leaves (textarea.test.tsx › Tab moves in and out and never inserts a tab).
  • 2.4.7 Focus Visible (AA): the focus ring.
  • 2.4.13 Focus Appearance (AAA): the ring's thickness and contrast. Not counted toward the AA bar.
  • 2.5.3 Label in Name (A): the visible label is the name.
  • 2.5.8 Target Size (Minimum) (AA): the box is far above 24px (the Default story's expectMinimumTargetSize).
  • 3.3.1 Error Identification (A) and 3.3.2 Labels or Instructions (A): through the Field. The count says the limit before the user hits it.
  • 4.1.2 Name, Role, Value (A): native role, name, aria-invalid, aria-required, disabled.
  • 4.1.3 Status Messages (AA): the count is announced politely through the Announcer (character-count.test.tsx › announcements (4.1.3)).

Keyboard#

Focus
native
Selection follows focus
n/a
Arrows wrap
n/a
Shortcuts
none

All native: Textarea handles no keys itself and never calls preventDefault on one. It never moves focus and never auto-advances. Tab leaves the box (it never inserts a tab character), and Enter is a line break: a <textarea> never submits its form. In a Field, the Field.Label, the description, the count, the help text and the Field.ErrorMessage are not Tab stops (see the Field page).

KeyWhereWhat happens
Tab / Shift+TabTextareaMoves focus in and out, in DOM order. Tab never inserts a tab character
Test: textarea.test.tsx › Tab moves in and out and never inserts a tab
EnterTextareaInserts a line break. It never submits the form
Test: textarea.test.tsx › Enter inserts a line break and does not submit
CharactersTextareaTypes them. Nothing is filtered, and nothing is cut at the limit
Test: textarea.test.tsx › typing calls onValueChange with the value and reason, and onChange too
Arrow keys / Home / End / PageUp / PageDownTextareaMove the caret (the browser's own: ArrowLeft and ArrowRight flip in RTL). Never intercepted
Test: textarea.test.tsx › caret keys are not intercepted, textarea.test.tsx › caret keys are not intercepted in right to left
Control/Command+ATextareaSelects all the text. Native
Test: textarea.test.tsx › Control/Command+A selects all the text
Control/Command+VTextareaPastes. Never blocked, and never cut by the limit: with characterCount the whole text is kept and the count says how many are over, so no text is lost without a message
Test: textarea.test.tsx › maxLength is the count’s limit and is not written as the native attribute, so a paste is never cut
EscapeTextareaDoes nothing: the value and the focus stay
Test: textarea.test.tsx › Escape does nothing: the value and the focus stay
No keyits Field.LabelA click on the label focuses the box (native <label for>)
Test: textarea.test.tsx › clicking the label focuses the box

Copy, cut and undo (Control/Command+C, X and Z) are native too. Textarea adds no shortcuts.

Announcements#

Textarea tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).

WhenWhat it saysMessage keyPoliteness
The count is at or past 80% of the limit and typing pauses (default 500 ms)characterCount.remaining count characterCount.over countPolite
The text crosses the limitcharacterCount.over countPolite

The text in all five languages

Change the text#

For your whole app, pass messages to KvirnProvider. For one Textarea, pass its messages prop.

<KvirnProvider messages={{ characterCount: { remaining: '…' } }}>

Warning: Don't forget

Announcements need a KvirnProvider around your app, outside any <form>, or an Announcer of your own. Without one nothing is announced, and a development warning says so.

API reference#

import { Textarea, CharacterCount, useTextarea, useCharacterCount } from '@kvirn-ui/react'

Textarea

Renders <textarea> with the role textbox (multi-line). It takes every attribute of a <textarea> except dir, which is the page’s, and passes ref to it. Put it in a Field: the label, description, help text and error are wired to it. The default theme is described on Theming.

PropTypeDefaultDescription
valuestring–Controlled: the value from your form state.
defaultValuestring–Uncontrolled: the native box keeps the value and a form submit sends it.
onValueChange(value: string, details: TextareaChangeDetails) => void–Called on every change. details has reason: "input" and the event, and with characterCount also length, limit and isOverLimit.
characterCountbooleanfalseShows how many characters are left under the box, with maxLength as the limit. Without maxLength it warns in development and shows nothing.
maxLengthnumber–With characterCount: the limit the count measures, not written as the native maxlength, so a paste is never cut. Without it: the native attribute.
countCharacters(value: string) => number–With characterCount: counts the text your own way, for example as your server does. Default: the characters the user sees.
messagesPartial<KvirnMessages['characterCount']>–With characterCount: overrides the count’s texts for this box.
rowsnumber5The height in lines. Where the browser supports it the box grows with its text and rows is its minimum.
disabledbooleanfalseNative disabled. A disabled Field disables the box too.
Class or attributeValuesMeaning
kv-textareaalwaysThe part class. The default theme styles it.
id, aria-describedbyin a FieldFrom the Field. aria-describedby lists the descriptions, the count and the help texts in DOM order, then the error, and your own ids after them.
aria-invalid"true" or absentIn a Field with invalid. Never set by the count: over the limit is a warning.
aria-required"true" or absentIn a Field with required.
data-invalid, data-required, data-disabledpresent or absentThe state of the Field.
data-focusedpresent or absentThe box has focus, however it got it.
data-focus-visiblepresent or absentThe box has keyboard focus.
data-overpresent or absentWith characterCount: the text is longer than the limit.

CharacterCount

Renders <p> with no role: a help text that says how much room is left. Textarea renders one for characterCount; use this part for the count under another control. It is not a live region: it is announced through the Announcer.

PropTypeDefaultDescription
valuestringRequiredThe text the count is about: the value of your box.
limitnumberRequiredThe most characters the text may have. At least 1.
countCharacters(value: string) => number–Counts the text your own way, so the count and your server agree. Default: the characters the user sees.
announceFromnumber0.8A share of the limit, 0 to 1, from which the count is announced.
announcementDebounceMillisecondsnumber500How long typing must pause before the count is announced. Crossing the limit is announced at once.
announceChangesbooleantrueWhether a change may be announced. Pass whether your box has focus, so a text set from code is silent.
messagesPartial<KvirnMessages['characterCount']>–Overrides the count’s texts: limit, remaining and over.
idstringgeneratedOutside a Field (also directly in a Fieldset): the id to list in your control’s aria-describedby. In a Field the Field gives it.
as'p' | 'div' | 'span''p'The element. The count is plain help text, never a heading. Another tag warns once.
Class or attributeValuesMeaning
kv-field-help-text, kv-character-countalwaysThe part classes: a help text’s look, and the count’s own.
data-overpresent or absentThe text is longer than the limit. The theme adds weight 600 and a warning icon.
data-nearpresent or absentFrom the announce threshold, and over the limit.
data-invalid, data-required, data-disabledpresent or absentThe state of the Field the count is in.

useTextarea

Options

PropTypeDefaultDescription
disabledbooleanfalseNative disabled. A disabled Field disables the box too.
rowsnumber5The height in lines.
onValueChange(value: string, details: TextareaChangeDetails) => void–Called on every change. It only reports: the value lives in your form state.

Result

PropTypeDefaultDescription
textareaPropsTextareaPartProps–Spread on a <textarea>: class, rows, the Field’s id, aria-describedby and state, and the handlers.
isInvalidboolean–Whether the Field is invalid.
isRequiredboolean–Whether the Field is required.
isDisabledboolean–Whether the box is disabled.
isFocusedboolean–Whether the box has focus.
isFocusVisibleboolean–Whether the box has keyboard focus.

useCharacterCount

The count’s props and text for your own element. It returns countProps (spread on a <p>), count (length, remaining, excess, isOver, isNear, isEmpty), text and isOver.

Options

PropTypeDefaultDescription
valuestringRequiredThe text the count is about: the value of your box.
limitnumberRequiredThe most characters the text may have. At least 1.
countCharacters(value: string) => number–Counts the text your own way, so the count and your server agree. Default: the characters the user sees.
announceFromnumber0.8A share of the limit, 0 to 1, from which the count is announced.
announcementDebounceMillisecondsnumber500How long typing must pause before the count is announced. Crossing the limit is announced at once.
announceChangesbooleantrueWhether a change may be announced. Pass whether your box has focus, so a text set from code is silent.
messagesPartial<KvirnMessages['characterCount']>–Overrides the count’s texts: limit, remaining and over.
idstringgeneratedOutside a Field (also directly in a Fieldset): the id to list in your control’s aria-describedby. In a Field the Field gives it.
refRef<HTMLElement>–The element’s ref. Pass it here: the hook also needs the element.

Strings

These are the default texts in @kvirn-ui/i18n.

For your whole app, pass messages to KvirnProvider. For one Textarea, pass its messages prop.

characterCount.limit

The count before the user types: how many characters fit.

LanguageDefault text
SvenskaDu kan skriva högst 500 tecken.
SuomiVoit kirjoittaa enintään 500 merkkiä.
Norsk bokmålDu kan skrive maks 500 tegn.
Norsk nynorskDu kan skrive maks 500 teikn.
EnglishYou can enter up to 500 characters.

characterCount.remaining

The count while the user types: how many characters are left.

LanguageDefault text
SvenskaDu har 120 tecken kvar.
SuomiSinulla on 120 merkkiä jäljellä.
Norsk bokmålDu har 120 tegn igjen.
Norsk nynorskDu har 120 teikn att.
EnglishYou have 120 characters remaining.

characterCount.over

The count past the limit: how many characters are too many.

LanguageDefault text
SvenskaDu har 12 tecken för mycket.
SuomiSinulla on 12 merkkiä liikaa.
Norsk bokmålDu har 12 tegn for mye.
Norsk nynorskDu har 12 teikn for mykje.
EnglishYou have 12 characters too many.

Known issues#

  • The direction is the page's. The Textarea has no dir prop and never sets dir="auto". It inherits the direction like every input: set it with the provider (dir, or an RTL locale) and put useLocale().localeProps where the language is set. A resident who writes Arabic in a left-to-right page gets left-aligned text; that is a page-language question, not a per-box one.
  • Auto-grow needs field-sizing: content and typed attr(). Elsewhere rows sets the height and the text scrolls inside, with a native scrollbar and a resize handle. There is no JavaScript auto-grow, by decision.
  • An uncontrolled box with characterCount doesn't see a value set from code. It counts typing, follows a native form reset, and reads the element's value on mount and on pageshow (the browser restores a form without an input event). A value you write to the element later is not seen: pass value.
  • Test the count with assistive technology. The debounce (500 ms) and the 80% threshold are worth testing with NVDA, VoiceOver, TalkBack and Dragon.
  • Keyboard tests run in Chromium only. The keyboard rows run in Vitest browser mode on Chromium, not in WebKit. Test in Safari with your own assistive technology.

Information: Did you know?

If one of these affects your service, put it in your accessibility statement, with the workaround.

Testing#

The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.

AT + browser + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apasstextarea.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)passn/apasstextarea.test.tsx › the Field’s label is the name, and its id links them; expectNoA11yViolations
Keyboard contract rows (Vitest browser)passn/apass8 rows, each names a test (textarea.test.tsx › Tab moves in and out and never inserts a tab)
Focus order and managementpassn/apasstextarea.test.tsx asserts focus (toHaveFocus); first rule: Tab moves in and out and never inserts a tab
Display modes (forced colours, 320px reflow, text spacing, reduced motion)passn/apassthe four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending

Research questions for the AT run: is the count read once with the value when the box gets focus, and not read again by the polite announcement at the same moment? Is a pause of 500 ms right, or does it interrupt a slow typist? Is "too many characters" understood as a warning without a visual cue? Does Dragon dictate a long text without the count lagging?

What to check#

With a screen reader and the keyboard, try:

  • Tab in: the label, the role and the count ("You can enter up to 500 characters.") are read.
  • Enter starts a new line and does not send the form. Tab leaves the box and types no tab character.
  • Type to 80% of the limit and pause: "You have N characters remaining." is said politely once, not on every key.
  • Paste past the limit: nothing is cut, and "You have N characters too many." is said at once.
  • Submit a text that is too long, with focus moved to the box: the error is read with the box.
  • At 200% zoom and in a Windows contrast theme the count and the over-limit warning stay visible.