Textarea

A multi-line input that grows as you type, in a small card with a send button. A counter keeps track of the characters and turns amber, then red, as the limit gets close.

64 / 280

Options

Size
Colour

Code

import { useLayoutEffect, useRef, useState } from "react";
import "./textarea.css";

/* A multi-line input that grows with its text, with a character counter and
   a send button under it.

   <Textarea label="Project details" limit={280} action="Send brief" value={text} onChange={setText} onSend={send} /> */
export function Textarea({ label, limit = 280, value, onChange, action = "Send", onSend, ...props }) {
  const area = useRef(null);
  const used = value.length;

  /* Grows the box where the browser cannot do it alone. */
  useLayoutEffect(() => {
    if (CSS.supports("field-sizing", "content")) return;
    area.current.style.height = "auto";
    area.current.style.height = area.current.scrollHeight + "px";
  }, [value]);

  return (
    <div
      className="dh-area"
      data-near={used >= limit * 0.9 && used < limit ? "" : undefined}
      data-full={used >= limit ? "" : undefined}
    >
      <label>
        <span>{label}</span>
        <textarea
          ref={area}
          rows={3}
          maxLength={limit}
          value={value}
          onChange={(event) => onChange(event.target.value)}
          {...props}
        />
      </label>
      <footer>
        <small aria-live="polite">
          <b>{used}</b> / {limit}
        </small>
        <button type="button" onClick={onSend}>
          {action}
        </button>
      </footer>
    </div>
  );
}

export function Example() {
  const [text, setText] = useState("We need a new site for our studio, with a small shop for prints.");
  return (
    <Textarea
      label="Project details"
      limit={280}
      action="Send brief"
      placeholder="Tell us what you have in mind"
      value={text}
      onChange={setText}
    />
  );
}
64 / 280