Forms & Events — Beginner React challenge.
Build a controlled textarea with a live character counter and a max-length guard from scratch: typing, pasting, and clearing all stay in sync with the counter — no libraries, no pre-built markup.
Requirements
- text is fully controlled via useState, starting empty.
- Any change (typing or pasting) that would exceed maxLength is clamped to exactly maxLength characters.
- The counter always reads '{length} / {maxLength}', updating on every change.
- Clear resets text back to empty and the counter back to '0 / {maxLength}'.
- The counter's text color switches to a warning color once length equals maxLength, and back to normal otherwise.
Signature
function CharCounterTextarea({ maxLength: number }): JSX.ElementExample
<CharCounterTextarea maxLength={200} />
// type "Hello world" -> textarea shows it, counter shows "11 / 200"
// paste 14 chars into a maxLength=10 field -> clamped to 10, counter turns red
// click Clear -> textarea empty, counter "0 / 200", normal colorConstraints
- Clamping must handle paste-length overflow, not just single-keystroke typing.
- The warning color only applies when length is exactly equal to maxLength (never over, since it's clamped).