Questionnaire
Asks one question at a time, with choices or free text, and collects the answers in a native form.
Installation
pnpm dlx shadcn@latest add @silkware/questionnaireTo copy the component by hand, install its dependencies:
pnpm add @shadcn/react class-variance-authority cn lucide-reactThen copy the source into components/ui/questionnaire.tsx. It also needs Button, for the navigation button styles:
"use client"
import * as React from "react"import { Questionnaire as QuestionnairePrimitive } from "@animate-ui/react/primitives/questionnaire"import { cn } from "cn"
import { buttonVariants, type Button } from "@/components/ui/button"import { CheckIcon } from "lucide-react"
function Questionnaire({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Root>) { return ( <QuestionnairePrimitive.Root data-slot="questionnaire" className={cn("flex w-full min-w-0 flex-col gap-6", className)} {...props} /> )}
function QuestionnaireProgress({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Progress>) { return ( <QuestionnairePrimitive.Progress data-slot="questionnaire-progress" className={cn( "min-h-[1lh] w-fit min-w-[14ch] text-xs font-medium text-muted-foreground tabular-nums", className )} {...props} /> )}
function QuestionnaireItem({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Item>) { return ( <QuestionnairePrimitive.Item data-slot="questionnaire-item" className={cn( "flex min-w-0 flex-col gap-5 border-0 p-0 outline-none", className )} {...props} /> )}
function QuestionnaireTitle({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Title>) { return ( <QuestionnairePrimitive.Title data-slot="questionnaire-title" className={cn( "font-heading text-base font-semibold text-pretty [&:not(:has(~[data-slot=questionnaire-description]))]:mb-5", className )} {...props} /> )}
function QuestionnaireDescription({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Description>) { return ( <QuestionnairePrimitive.Description data-slot="questionnaire-description" className={cn("text-sm text-pretty text-muted-foreground", className)} {...props} /> )}
function QuestionnaireChoices({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Choices>) { return ( <QuestionnairePrimitive.Choices data-slot="questionnaire-choices" className={cn( "group/questionnaire-choices grid min-w-0 gap-3", className )} {...props} /> )}
function QuestionnaireChoice({ children, className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Choice>) { return ( <QuestionnairePrimitive.Choice data-slot="questionnaire-choice" className={cn( "group/questionnaire-choice relative flex min-h-11 cursor-pointer items-start gap-3 rounded-md border border-input bg-transparent px-4 py-3.5 text-start text-sm shadow-xs transition-colors outline-none select-none hover:bg-muted/50 has-[>input:focus-visible]:border-ring has-[>input:focus-visible]:ring-3 has-[>input:focus-visible]:ring-ring/50 data-invalid:border-destructive dark:bg-input/20 data-checked:border-primary/40 data-checked:bg-muted dark:data-checked:bg-muted", "data-disabled:pointer-events-none data-disabled:cursor-not-allowed data-disabled:opacity-50", className )} {...props} > <QuestionnairePrimitive.ChoiceInput data-slot="questionnaire-choice-input" className="absolute inset-0 z-10 size-full cursor-pointer opacity-0" /> <span aria-hidden="true" data-slot="questionnaire-choice-indicator" className="pointer-events-none relative flex size-4 shrink-0 translate-y-[--spacing(0.45)] items-center justify-center rounded-[4px] border border-input group-has-data-[slot=questionnaire-choice-description]/questionnaire-choice:translate-y-0.5 group-data-[type=radio]/questionnaire-choice:rounded-full group-data-checked/questionnaire-choice:border-primary group-data-checked/questionnaire-choice:bg-primary group-data-checked/questionnaire-choice:text-primary-foreground dark:bg-input/30 dark:group-data-checked/questionnaire-choice:bg-primary" > <span data-slot="questionnaire-choice-indicator-dot" className="hidden size-2 rounded-full bg-primary-foreground group-data-[type=checkbox]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block" /> <CheckIcon data-slot="questionnaire-choice-indicator-check" className="hidden size-3.5 group-data-[type=radio]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block" /> </span> <QuestionnairePrimitive.ChoiceLabel data-slot="questionnaire-choice-label" className="flex min-w-0 flex-1 flex-col gap-1 leading-snug" > {children} </QuestionnairePrimitive.ChoiceLabel> <QuestionnairePrimitive.ChoiceShortcut data-slot="questionnaire-choice-shortcut" className="pointer-events-none ms-auto hidden size-5 shrink-0 translate-y-[--spacing(0.45)] items-center justify-center rounded-md border border-input bg-background font-mono text-[0.625rem] leading-none font-medium text-muted-foreground shadow-xs group-has-data-[slot=questionnaire-choice-description]/questionnaire-choice:translate-y-0.5 group-data-[shortcut]/questionnaire-choice:inline-flex" /> </QuestionnairePrimitive.Choice> )}
function QuestionnaireChoiceDescription({ className, ...props}: React.ComponentProps<"span">) { return ( <span data-slot="questionnaire-choice-description" className={cn("text-muted-foreground", className)} {...props} /> )}
function QuestionnaireInput({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Input>) { return ( <div data-slot="questionnaire-input-wrapper" className="group/questionnaire-input relative w-full min-w-0" > <QuestionnairePrimitive.Input data-slot="questionnaire-input" className={cn( "h-9 min-h-11 w-full min-w-0 rounded-md border border-input bg-transparent px-2.5 py-1 text-base shadow-xs transition-[color,box-shadow,background-color] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 sm:min-h-0 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", "selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground", className )} {...props} /> </div> )}
function QuestionnaireError({ className, ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Error>) { return ( <QuestionnairePrimitive.Error data-slot="questionnaire-error" className={cn("text-sm text-destructive", className)} {...props} /> )}
function QuestionnaireActions({ className, ...props}: React.ComponentProps<"div">) { return ( <div data-slot="questionnaire-actions" className={cn( "grid min-h-11 w-full grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2 sm:min-h-9", className )} {...props} /> )}
function QuestionnairePrevious({ children, className, size = "default", variant = "outline", ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Previous> & Pick<React.ComponentProps<typeof Button>, "size" | "variant">) { return ( <QuestionnairePrimitive.Previous data-slot="questionnaire-previous" data-size={size} data-variant={variant} className={cn( buttonVariants({ size, variant }), "col-start-1 row-start-1 min-h-11 justify-self-start sm:min-h-0", className )} {...props} > {children ?? "Previous"} </QuestionnairePrimitive.Previous> )}
function QuestionnaireSkip({ children, className, size = "default", variant = "outline", ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Skip> & Pick<React.ComponentProps<typeof Button>, "size" | "variant">) { return ( <QuestionnairePrimitive.Skip data-slot="questionnaire-skip" data-size={size} data-variant={variant} className={cn( buttonVariants({ size, variant }), "col-start-2 row-start-1 min-h-11 justify-self-end sm:min-h-0", className )} {...props} > {children ?? "Skip"} </QuestionnairePrimitive.Skip> )}
function QuestionnaireNext({ children, className, size = "default", variant = "default", ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Next> & Pick<React.ComponentProps<typeof Button>, "size" | "variant">) { return ( <QuestionnairePrimitive.Next data-slot="questionnaire-next" data-size={size} data-variant={variant} className={cn( buttonVariants({ size, variant }), "col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0", className )} {...props} > {children ?? "Next"} </QuestionnairePrimitive.Next> )}
function QuestionnaireSubmit({ children, className, size = "default", variant = "default", ...props}: React.ComponentProps<typeof QuestionnairePrimitive.Submit> & Pick<React.ComponentProps<typeof Button>, "size" | "variant">) { return ( <QuestionnairePrimitive.Submit data-slot="questionnaire-submit" data-size={size} data-variant={variant} className={cn( buttonVariants({ size, variant }), "col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0", className )} {...props} > {children ?? "Submit"} </QuestionnairePrimitive.Submit> )}
export { Questionnaire, QuestionnaireActions, QuestionnaireChoice, QuestionnaireChoiceDescription, QuestionnaireChoices, QuestionnaireDescription, QuestionnaireError, QuestionnaireInput, QuestionnaireItem, QuestionnaireNext, QuestionnairePrevious, QuestionnaireProgress, QuestionnaireSkip, QuestionnaireSubmit, QuestionnaireTitle,}The behaviour comes from the headless @shadcn/react/questionnaire primitive. The component only adds the Silkware styles. It does not use React Aria, so this page has no primitive link.
Usage
import { Questionnaire, QuestionnaireActions, QuestionnaireChoice, QuestionnaireChoices, QuestionnaireError, QuestionnaireItem, QuestionnaireNext, QuestionnairePrevious, QuestionnaireProgress, QuestionnaireSubmit, QuestionnaireTitle,} from "@/components/ui/questionnaire"const items = [ { name: "site", required: true }, { name: "line-stopped", required: true },] as const
<Questionnaire items={items} onSubmit={handleSubmit}> <QuestionnaireProgress /> <QuestionnaireItem name="site" required> <QuestionnaireTitle>Where did the defect occur?</QuestionnaireTitle> <QuestionnaireChoices> <QuestionnaireChoice value="bergamo">Bergamo plant</QuestionnaireChoice> <QuestionnaireChoice value="brescia">Brescia plant</QuestionnaireChoice> </QuestionnaireChoices> <QuestionnaireError /> </QuestionnaireItem> <QuestionnaireItem name="line-stopped" required> <QuestionnaireTitle>Is the line stopped?</QuestionnaireTitle> <QuestionnaireChoices> <QuestionnaireChoice value="yes">Yes</QuestionnaireChoice> <QuestionnaireChoice value="no">No</QuestionnaireChoice> </QuestionnaireChoices> <QuestionnaireError /> </QuestionnaireItem> <QuestionnaireActions> <QuestionnairePrevious /> <QuestionnaireNext /> <QuestionnaireSubmit>Report defect</QuestionnaireSubmit> </QuestionnaireActions></Questionnaire>function handleSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault() const data = new FormData(event.currentTarget) const site = data.get("site")}Questionnaire renders a native <form>. Only one item is visible at a time; the others are hidden and inert. Each item's name is the name of its answer controls, so FormData.get(name) returns a single answer and FormData.getAll(name) returns the answers of an item with multiple. Skipped items are absent from the form data.
Pass the same items array to Questionnaire so the active item, the progress and the shortcuts are correct on the server render. Each entry needs a name, and may set required, disabled and choices (an array of { value }). The collection must match the items you render, in the same order and with the same names.
Do not put a Questionnaire inside another form, and do not nest items: the questionnaire owns navigation and validation, and the page around it owns saving the answers.
Examples
Multiple selection
Put multiple on QuestionnaireItem to turn its choices into checkboxes. Read the answers with getAll. Pair it with a description that says people can pick more than one.
Free text answer
Add a QuestionnaireInput inside QuestionnaireChoices so people can write an answer the choices do not cover. The answer is read with the same name as the fixed choices. Give the input an aria-label or a visible label.
Optional item and skip
An item without required can be skipped. Add QuestionnaireSkip to the actions. It appears only on optional items, and a required item cannot be skipped. Say in the description that the item is optional.
Shortcuts
shortcuts="letters" assigns the keys A, B, C and so on to the answers of the active item, and shortcuts="numbers" assigns 1, 2, 3, up to 9. Each choice shows its key. Pressing the key picks that choice. Shortcuts pause while people type in a text field.
Controlled item
Use item and onItemChange to control which question is shown, for example to move back to an invalid answer or to save the position. Use defaultItem to start on another item and let the questionnaire manage the rest.
Active item: site
Accessibility
| Key | Action |
|---|---|
| Tab | Moves focus between the answer controls and the visible actions. |
| ShiftTab | Moves focus to the previous control or action. |
| ArrowUp | Moves to the previous answer. Native radio buttons also select it. |
| ArrowDown | Moves to the next answer. Native radio buttons also select it. |
| ArrowLeft | Moves to the previous item when focus is not in a radio group or a text field. |
| ArrowRight | Moves to the next item when the active one is answered or skipped, and focus is not in a radio group or a text field. |
| Space | Selects a radio button, toggles a checkbox or presses the focused action. |
| Enter | Continues from a selected choice or a filled text field, or presses the focused action. |
| CtrlEnter | Validates and continues from anywhere in the questionnaire, or submits on the last item. |
| A | With shortcuts set to letters, picks the first answer. B picks the second, and so on. |
On macOS, Command works in place of Ctrl. Arrow and shortcut keys pause while people type in a text field.
The component provides:
- A
fieldsetper item, withQuestionnaireTitleas itslegend, and descriptions and errors linked witharia-describedby. - Native radio buttons and checkboxes for the choices, so screen readers, form submission and the platform keyboard behaviour work as they do anywhere.
- A progress bar with an accessible name, and
aria-invalidon an invalid item and its controls. - Inactive items and actions hidden and inert. After a successful move, focus goes to the new item. After a failed validation, focus goes to the first answer control.
aria-keyshortcutsfor the assigned keys and the available navigation.
You provide:
- A
QuestionnaireTitlein every item. It is the name of the group. - A name for every
QuestionnaireInput, with a visibleLabelandhtmlForor anaria-label. A placeholder is not a label. - A
QuestionnaireErrorin every required item, so a failed validation shows a message. - Choice text that is complete on its own, because a screen reader reads each choice out of context.
Guidelines
When to use
- To collect a few related answers one step at a time: a defect report, a check at goods receipt, a short triage.
- When each answer is a choice from a short list, with at most one free text field.
- When a step by step flow is easier to complete than a long form, for example on a phone.
When not to use
- For a long form with many fields, or fields that people fill in any order. Use Field in a form.
- For a single choice with no follow-up. Use a Radio Group or a Select.
- For a survey with a rating or a table of answers. Questionnaire handles choices and text only.
- For a flow that branches in a way that depends on the server. Control the active item with
itemandonItemChange, and keep the logic in your page. - To walk through a product with steps and tips. Use a Dialog or a Popover.
Content
- Write the title as a direct question: "Is the line stopped?".
- Keep choices to a few words and start them with the same kind of word. Use sentence case.
- Say in the description whether an answer is optional or whether people can choose several.
- Put "Other" last as a text input with a name, not as a choice that opens another step.
- Name the submit button after what happens: "Report defect", not "Submit".
Questions and choices
Ask one clear question and give choices people can answer without thinking.
Don’t use a title that is a single word and choices such as "Option 1". People cannot tell what is being asked.
API reference
The parts come from @shadcn/react/questionnaire. Each one accepts the props of the element it renders, className, and a render prop to replace that element. The headless docs are in the @shadcn/react Questionnaire reference.
Questionnaire
The root. It renders a native <form> and owns the active item, the answers, validation and progress.
| Prop | Type | Default | Description |
|---|---|---|---|
items? | readonly { name: string; required?: boolean; disabled?: boolean; choices?: readonly { value: string; disabled?: boolean }[] }[] | None | The items in order. Needed for server rendering of the active item, progress, actions and shortcuts. |
item? | string | None | The name of the active item, for a controlled questionnaire. |
defaultItem? | string | first enabled item | The item shown first when the questionnaire is uncontrolled. |
onItemChange? | (item: string) => void | None | Called when navigation moves to another item. |
shortcuts? | "letters" | "numbers" | None | Assigns a key to each answer of the active item. |
noValidate? | boolean | true | Turns off the browser's own validation messages so QuestionnaireError shows them. |
onSubmit? | (event: FormEvent<HTMLFormElement>) => void | None | Called when the last item is submitted and every item is valid. |
onReset? | (event: FormEvent<HTMLFormElement>) => void | None | Called on form reset. Prevent the default to keep the answers. |
QuestionnaireProgress
Shows the position, "Question 1 of 2" by default, as a progress bar with an accessible name.
| Prop | Type | Default | Description |
|---|---|---|---|
children? | ReactNode | None | Replaces the default text. |
aria-label? | string | "Questionnaire progress" | The accessible name of the progress bar. |
render? | ReactElement | (props, state) => ReactElement | None | Renders custom progress. The state holds current, total, first and last. |
QuestionnaireItem
One question. It renders a <fieldset>.
| Prop | Type | Default | Description |
|---|---|---|---|
name | string | None | The unique name of the item and of its answer controls in the form. |
required? | boolean | false | Requires an answer and hides Skip. |
multiple? | boolean | false | Renders the fixed choices as checkboxes. |
disabled? | boolean | false | Leaves the item out of the progress and the navigation. |
invalid? | boolean | false | Marks the item invalid from your own validation. |
onStatusChange? | (status: "unanswered" | "answered" | "skipped") => void | None | Called when the item is answered, cleared or skipped. |
QuestionnaireTitle and QuestionnaireDescription
QuestionnaireTitle renders the legend of the item. QuestionnaireDescription renders a <p> linked to the item with aria-describedby.
QuestionnaireChoices
A layout container for the choices and the free text input of an item.
QuestionnaireChoice
One fixed answer: a native radio button, or a checkbox when the item is multiple, with the row as its label. It renders a <label> and shows an indicator and, with shortcuts, the key.
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | None | The value submitted when the choice is selected. |
checked? | boolean | None | Whether the choice is selected, for a controlled choice. |
defaultChecked? | boolean | false | Whether the choice starts selected. |
disabled? | boolean | false | Disables the choice. |
onChange? | ChangeEventHandler<HTMLInputElement> | None | Called when the native input changes. |
QuestionnaireChoiceDescription
A muted <span> for a second line inside a choice, under its label.
QuestionnaireInput
A free text answer, a native input inside a wrapper. Its name is set by the item.
| Prop | Type | Default | Description |
|---|---|---|---|
type? | string | "text" | A text entry type such as "email", "number" or "date". |
value? | string | number | readonly string[] | None | The value, for a controlled input. |
defaultValue? | string | number | readonly string[] | None | The initial value. |
disabled? | boolean | false | Disables the input. |
aria-label? | string | None | The accessible name, required without a visible label. |
QuestionnaireError
The validation message of the item. It is hidden until the item fails validation and shows a message for the failure by default. Pass children to write your own.
QuestionnaireActions
A grid that lays out the navigation buttons in one row: Previous at the start, Skip and Next or Submit at the end. It renders a <div>.
QuestionnairePrevious, QuestionnaireSkip, QuestionnaireNext and QuestionnaireSubmit
Native buttons with the button styles. They stay in the DOM and show or hide with the state: Previous after the first item, Skip on optional items, Next before the last item and Submit on the last. They stay enabled so that pressing one can reveal a validation error.
| Prop | Type | Default | Description |
|---|---|---|---|
variant? | "default" | "secondary" | "outline" | "ghost" | "destructive" | "link" | None | The button variant. Previous and Skip default to "outline", Next and Submit to "default". |
size? | "xs" | "sm" | "default" | "lg" | "icon-xs" | "icon-sm" | "icon" | "icon-lg" | "default" | The button size. The icon sizes make a square button, so use them only with an icon and an aria-label. |
children? | ReactNode | None | The label. Defaults to "Previous", "Skip", "Next" and "Submit". |
disabled? | boolean | false | Disables the button. |