Skip to main content

Input

A headless input component providing accessible form input primitives with zero styling opinions. Pair it with the Field primitive to get label, description, and error-message wiring with coordinated ARIA IDs.

Live Demo​

JavaScript
<Field.Root className='input-demo-container' invalid>
<Field.Label className='label'>Label</Field.Label>
<Input.Root>
  <Input.Field className='input' />
</Input.Root>
<Field.Description className='description'>
  Helper text for guidance
</Field.Description>
<Field.ErrorMessage className='error'>
  This field is required
</Field.ErrorMessage>
</Field.Root>

The live demo shows the recommended pattern: a Field wrapper supplying label, helper text, and error message wiring around the Input primitive.

Features​

  • ✅ Text input and textarea support via polymorphic rendering (input or textarea)
  • ✅ Reads validation, disabled, required, and read-only state from a parent Field automatically (direct props still override)
  • ✅ Focus state tracking on the input element
  • ✅ Form integration with name, value, and change event support
  • ✅ Works standalone or composed with Field, Label, and custom layout wrappers

Import​

import { Field, Input } from '@turkish-technology/spar';

Input and Input.Root refer to the same component — the difference is only notation style. Label, description, and error message are owned by the Field primitive:

// Dot notation
<Field.Root>
<Field.Label />
<Input.Root>
<Input.Field />
</Input.Root>
<Field.Description />
<Field.ErrorMessage />
</Field.Root>;

// Named import style
import {
Field,
FieldLabel,
FieldDescription,
FieldErrorMessage,
Input,
InputField,
} from '@turkish-technology/spar';

<Field>
<FieldLabel />
<Input>
<InputField />
</Input>
<FieldDescription />
<FieldErrorMessage />
</Field>;

Anatomy​

The Input component focuses on the field element itself. Label, description, and error message are provided by the Field primitive, which shares ARIA IDs and state with Input via context.

Helper text for guidance
Parts
Field.RootField context provider (label, description, error wiring)
Field.LabelAccessible label, auto-linked via htmlFor
Input.RootInput context provider for visual state
Input.FieldCore input element (input/textarea)
Field.DescriptionHelper text for guidance
Field.ErrorMessageError announcement with role="alert"

Structure​

<Field.Root>
<Field.Label />
<Input.Root>
<Input.Field />
</Input.Root>
<Field.Description />
<Field.ErrorMessage />
</Field.Root>

Data Flow:

  • Field.Root: Owns coordinated IDs and the invalid / disabled / required / readOnly state, propagated via context
  • Field.Label: Accessible <label> auto-linked to the input via htmlFor
  • Input.Root: Provides visual-input context; inherits state from the enclosing Field when present
  • Input.Field: Core input element with polymorphic support (input/textarea)
  • Field.Description: Helper text linked via aria-describedby
  • Field.ErrorMessage: Error announcement with role="alert", only rendered when invalid is true

Code Examples​

Basic Text Input​

A simple text input with label and description for user guidance.

function BasicTextInput() {
const [value, setValue] = React.useState('');

return (
<Field.Root>
<Field.Label>Email Address</Field.Label>
<Input.Root>
<Input.Field
type="email"
value={value}
onChange={e => setValue(e.target.value)}
placeholder="Enter your email"
/>
</Input.Root>
<Field.Description>
We'll use this to send you important updates
</Field.Description>
</Field.Root>
);
}

Input with Validation​

Demonstrates validation state management with conditional error message display.

function ValidatedInput() {
const [email, setEmail] = React.useState('');
const [invalid, setInvalid] = React.useState(false);

const handleSubmit = () => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
setInvalid(!emailRegex.test(email));
};

return (
<div>
<Field.Root invalid={invalid} required>
<Field.Label>Email Address</Field.Label>
<Input.Root>
<Input.Field
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="user@example.com"
/>
</Input.Root>
<Field.Description>
Enter a valid email address for account verification
</Field.Description>
<Field.ErrorMessage>
Please enter a valid email address
</Field.ErrorMessage>
</Field.Root>
<button type="button" onClick={handleSubmit}>
Validate Email
</button>
</div>
);
}

Textarea Input​

Shows polymorphic rendering capability for multi-line text input with proper accessibility.

function TextareaInput() {
const [message, setMessage] = React.useState('');

return (
<Field.Root>
<Field.Label>Message</Field.Label>
<Input.Root>
<Input.Field
as="textarea"
value={message}
onChange={e => setMessage(e.target.value)}
rows={4}
placeholder="Enter your message here..."
/>
</Input.Root>
<Field.Description>
Maximum 500 characters ({message.length}/500)
</Field.Description>
</Field.Root>
);
}

Disabled Input​

Demonstrates disabled state propagation from Field down to Input automatically.

function DisabledInput() {
return (
<Field.Root disabled>
<Field.Label>Account Type</Field.Label>
<Input.Root>
<Input.Field value="Premium Account" readOnly />
</Input.Root>
<Field.Description>
Contact support to change your account type
</Field.Description>
</Field.Root>
);
}

Form Integration​

Complete form example with validation, submission, and error handling.

function ContactForm() {
const [formData, setFormData] = React.useState({
name: '',
email: '',
message: '',
});
const [errors, setErrors] = React.useState<Record<string, string>>({});

const validateForm = () => {
const newErrors: Record<string, string> = {};
if (!formData.name) newErrors.name = 'Name is required';
if (!formData.email) newErrors.email = 'Email is required';
else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
newErrors.email = 'Please enter a valid email';
}
if (!formData.message) newErrors.message = 'Message is required';
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};

const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (validateForm()) {
console.log('Form submitted:', formData);
}
};

return (
<form onSubmit={handleSubmit} noValidate>
<Field.Root invalid={!!errors.name} required>
<Field.Label>Full Name</Field.Label>
<Input.Root>
<Input.Field
name="name"
value={formData.name}
onChange={e => setFormData({ ...formData, name: e.target.value })}
/>
</Input.Root>
<Field.ErrorMessage>{errors.name}</Field.ErrorMessage>
</Field.Root>

<Field.Root invalid={!!errors.email} required>
<Field.Label>Email</Field.Label>
<Input.Root>
<Input.Field
type="email"
name="email"
value={formData.email}
onChange={e => setFormData({ ...formData, email: e.target.value })}
/>
</Input.Root>
<Field.ErrorMessage>{errors.email}</Field.ErrorMessage>
</Field.Root>

<Field.Root invalid={!!errors.message} required>
<Field.Label>Message</Field.Label>
<Input.Root>
<Input.Field
as="textarea"
name="message"
rows={4}
value={formData.message}
onChange={e =>
setFormData({ ...formData, message: e.target.value })
}
/>
</Input.Root>
<Field.ErrorMessage>{errors.message}</Field.ErrorMessage>
</Field.Root>

<button type="submit">Send Message</button>
</form>
);
}

API Reference​

Input / Input.Root​

The root context provider that wraps all compound input parts. Input and Input.Root are the same component - the difference is only import/notation style. Renders a <div> by default and exposes an InputContext that all child components consume.

Props

NameTypeDefaultDescription
id?stringundefinedBase ID used to derive sub-element IDs. Auto-generated when omitted.
as?React.ElementType'div'Element type for the root wrapper
ref?React.Ref<T>undefinedRef for the root wrapper element
childrenReact.ReactNode-Compound input elements
invalid?booleanfalseValidation state propagated to all compound parts
disabled?booleanfalseDisabled state propagated to all compound parts
required?booleanfalseRequired state propagated to all compound parts
readOnly?booleanfalseRead-only state propagated to all compound parts
...propsReact.ComponentProps<T>-All standard HTML attributes for the root element

HTML Attributes

AttributeValuePurpose
data-invalid"" | undefinedIndicates validation state
data-disabled"" | undefinedIndicates disabled state
data-required"" | undefinedIndicates required state
data-readonly"" | undefinedIndicates read-only state

Input.Field​

The core input element with polymorphic rendering support. Handles focus states, validation attributes, and ARIA associations automatically.

Props

NameTypeDefaultDescription
as?React.ElementType'input'Element type for polymorphic rendering
ref?React.ComponentPropsWithRef<T>['ref']undefinedRef for the input element
autoFocus?booleanfalseWhether to focus the input on mount
onFocus?(event: React.FocusEvent<HTMLElement>) => voidundefinedFocus event handler
onBlur?(event: React.FocusEvent<HTMLElement>) => voidundefinedBlur event handler

Events

NameParametersDescriptionWhen Triggered
onFocus(event: React.FocusEvent<HTMLElement>)Input gains focusUser clicks or tabs to input
onBlur(event: React.FocusEvent<HTMLElement>)Input loses focusUser clicks away or tabs to next element
onChange(event: React.ChangeEvent<HTMLElement>)Input value changesUser types or modifies input content

HTML Attributes

AttributeValuePurpose
idstringUnique field identifier; auto-assigned from context when inside Input.Root
data-focused"" | undefinedIndicates focus state
data-autofocus"" | undefinedIndicates auto-focus state
data-disabled"" | undefinedIndicates disabled state
data-required"" | undefinedIndicates required state
data-readonly"" | undefinedIndicates read-only state

Label, Description, and Error Message​

Label, helper text, and validation messaging are not part of Input. Use the Field primitive — Field.Label, Field.Description, and Field.ErrorMessage — which share coordinated ARIA IDs and state (invalid, disabled, required, readOnly) with the enclosed Input via context.

Keyboard Interactions​

Complete keyboard behavior for the Input component:

KeyActionContextNotes
TabNavigate forwardAlwaysMoves focus to the input field or next focusable element
Shift + TabNavigate backwardAlwaysMoves focus to previous focusable element
EnterSubmit formForm contextSubmits parent form when input is focused
BackspaceDelete characterText inputRemoves character before cursor
DeleteDelete characterText inputRemoves character after cursor
HomeMove to startText inputMoves cursor to beginning of text
EndMove to endText inputMoves cursor to end of text
ArrowLeftMove leftText inputMoves cursor one character left
ArrowRightMove rightText inputMoves cursor one character right
Ctrl + ASelect allText inputSelects all text in input
Ctrl + CCopyText selectedCopies selected text to clipboard
Ctrl + XCutText selectedCuts selected text to clipboard
Ctrl + VPasteText inputPastes text from clipboard
Ctrl + ZUndoText inputUndoes last edit operation