# Label

Form label with consistent styling and optional required or optional markers that screen readers announce correctly.

- Category: Form
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/label.json
- CLI: `npx markasui@latest add label`

## When to use

Labels for form controls that do not render their own label, or for custom controls and field groups.

- Always link the label to a control with for and id, or wrap the control inside the label
- Also set the required attribute on the control itself; the label marker is only visual and spoken text
- Mark either required or optional fields in one form, whichever group is smaller, not both

## Code

### Blade

Save at `resources/views/components/markas/label.blade.php`. No extra dependencies.

```blade
@props([
    'required' => false,
    'optional' => false,
    'requiredLabel' => 'required',
    'optionalLabel' => 'Optional',
])

@php
    $base = 'text-sm font-medium text-ink';
    $marker = 'ms-0.5 text-danger';
    $srOnly = 'sr-only';
    $optionalClass = 'font-normal text-muted';
@endphp

<label {{ $attributes->class([$base]) }}>{{ $slot }}@if ($required)<span aria-hidden="true" class="{{ $marker }}">*</span>{{ ' ' }}<span class="{{ $srOnly }}">{{ $requiredLabel }}</span>@elseif ($optional){{ ' ' }}<span class="{{ $optionalClass }}">{{ $optionalLabel }}</span>@endif</label>
```

```blade
<x-markas.label for="full_name" required>Full name</x-markas.label>
<input id="full_name" name="full_name" required />

<x-markas.label for="company" optional>Company</x-markas.label>
<input id="company" name="company" />
```

### React

Save at `src/components/markas/Label.tsx`. No extra dependencies.

```tsx
import type { ComponentProps } from "react";

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

export type LabelProps = ComponentProps<"label"> & {
  required?: boolean;
  optional?: boolean;
  requiredLabel?: string;
  optionalLabel?: string;
};

export function Label({
  required = false,
  optional = false,
  requiredLabel = "required",
  optionalLabel = "Optional",
  className,
  children,
  ...props
}: LabelProps) {
  return (
    <label className={cx(base, className)} {...props}>
      {children}
      {required ? (
        <>
          <span aria-hidden="true" className={marker}>
            *
          </span>{" "}
          <span className={srOnly}>{requiredLabel}</span>
        </>
      ) : optional ? (
        <>
          {" "}
          <span className={optionalClass}>{optionalLabel}</span>
        </>
      ) : null}
    </label>
  );
}
```

```tsx
import { Label } from "@/components/markas/Label";

<Label htmlFor="full_name" required>Full name</Label>
<input id="full_name" name="full_name" required />

<Label htmlFor="company" optional>Company</Label>
<input id="company" name="company" />
```

### Vue

Save at `src/components/markas/Label.vue`. No extra dependencies.

```vue
<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    required?: boolean;
    optional?: boolean;
    requiredLabel?: string;
    optionalLabel?: string;
  }>(),
  {
    required: false,
    optional: false,
    requiredLabel: "required",
    optionalLabel: "Optional",
  },
);

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";
</script>

<template>
  <label :class="base"
    ><slot /><template v-if="props.required"
      ><span aria-hidden="true" :class="marker">*</span>{{ " "
      }}<span :class="srOnly">{{ props.requiredLabel }}</span></template
    ><template v-else-if="props.optional"
      >{{ " "
      }}<span :class="optionalClass">{{ props.optionalLabel }}</span></template
    ></label
  >
</template>
```

```vue
<script setup lang="ts">
import Label from "@/components/markas/Label.vue";
</script>

<template>
  <Label for="full_name" required>Full name</Label>
  <input id="full_name" name="full_name" required />

  <Label for="company" optional>Company</Label>
  <input id="company" name="company" />
</template>
```

### Svelte

Save at `src/lib/components/markas/Label.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLLabelAttributes } from "svelte/elements";

  const base = "text-sm font-medium text-ink";
  const marker = "ms-0.5 text-danger";
  const srOnly = "sr-only";
  const optionalClass = "font-normal text-muted";

  type Props = HTMLLabelAttributes & {
    required?: boolean;
    optional?: boolean;
    requiredLabel?: string;
    optionalLabel?: string;
    children?: Snippet;
  };

  let {
    required = false,
    optional = false,
    requiredLabel = "required",
    optionalLabel = "Optional",
    class: className,
    children,
    ...rest
  }: Props = $props();
</script>

<label class={[base, className]} {...rest}
  >{@render children?.()}{#if required}<span aria-hidden="true" class={marker}
      >*</span
    >{" "}<span class={srOnly}>{requiredLabel}</span
    >{:else if optional}{" "}<span class={optionalClass}>{optionalLabel}</span
    >{/if}</label
>
```

```svelte
<script lang="ts">
  import Label from "$lib/components/markas/Label.svelte";
</script>

<Label for="full_name" required>Full name</Label>
<input id="full_name" name="full_name" required />

<Label for="company" optional>Company</Label>
<input id="company" name="company" />
```

### Astro

Save at `src/components/markas/Label.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";

type Props = HTMLAttributes<"label"> & {
  required?: boolean;
  optional?: boolean;
  requiredLabel?: string;
  optionalLabel?: string;
};

const {
  required = false,
  optional = false,
  requiredLabel = "required",
  optionalLabel = "Optional",
  class: className,
  ...rest
} = Astro.props;
---

<label class:list={[base, className]} {...rest}><slot />{required ? <Fragment><span aria-hidden="true" class={marker}>*</span>{" "}<span class={srOnly}>{requiredLabel}</span></Fragment> : optional ? <Fragment>{" "}<span class={optionalClass}>{optionalLabel}</span></Fragment> : null}</label>
```

```astro
---
import Label from "@/components/markas/Label.astro";
---

<Label for="full_name" required>Full name</Label>
<input id="full_name" name="full_name" required />

<Label for="company" optional>Company</Label>
<input id="company" name="company" />
```

### Angular

Save at `src/app/markas/label.component.ts`. No extra dependencies.

```ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  input,
} from "@angular/core";

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";

/**
 * Attribute selector on the native label: for, id, and the user's class stay on the label
 * itself, so nothing has to be forwarded.
 */
@Component({
  selector: "label[markas-label]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "[class]": "base" },
  // Kept on one line: formatting would add whitespace text around the marker and the optional text.
  // prettier-ignore
  template: `<ng-content />@if (required()) {<span aria-hidden="true" [class]="marker">*</span>{{ " " }}<span [class]="srOnly">{{ requiredLabel() }}</span>} @else if (optional()) {{{ " " }}<span [class]="optionalClass">{{ optionalLabel() }}</span>}`,
})
export class Label {
  readonly required = input(false, { transform: booleanAttribute });
  readonly optional = input(false, { transform: booleanAttribute });
  /** Screen reader text after the required marker. */
  readonly requiredLabel = input("required");
  /** Visible text after an optional label. */
  readonly optionalLabel = input("Optional");

  protected readonly base = base;
  protected readonly marker = marker;
  protected readonly srOnly = srOnly;
  protected readonly optionalClass = optionalClass;
}
```

```ts
import { Component } from "@angular/core";
import { Label } from "./markas/label.component";

@Component({
  selector: "app-profile-form",
  imports: [Label],
  template: `
    <label markas-label for="full_name" required>Full name</label>
    <input id="full_name" name="full_name" required />

    <label markas-label for="company" optional>Company</label>
    <input id="company" name="company" />
  `,
})
export class ProfileForm {}
```

In Angular, Label is an attribute on a native `<label>`, so `for`, `id`, and `class` stay on that element.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `for / htmlFor` | `string` | - | Id of the form control this label names. React uses htmlFor. In Angular, Label is an attribute on a native label (<label markas-label for="...">). |
| `required` | `boolean` | false | Shows a red asterisk (hidden from screen readers) and a screen reader only text from requiredLabel. Takes priority over optional. |
| `optional` | `boolean` | false | Shows muted text from optionalLabel after the label text. |
| `requiredLabel` | `string` | required | Screen reader text announced for required fields. |
| `optionalLabel` | `string` | Optional | Visible text shown for optional fields. |

## Accessibility

- Renders a native label element, so clicking it focuses or toggles the linked control.
- The asterisk is aria-hidden; the required state is announced through screen reader only text instead.
- The optional text is part of the label, so it is included in the accessible name of the control.

## Notes

- Label needs no JavaScript. Extra attributes and `class` go to the `<label>` element, and your classes come last.
- You can also wrap a checkbox or radio inside the label instead of using `for`: `<Label class="flex items-center gap-2"><input type="checkbox" />Remember me</Label>`.
- The asterisk is hidden from screen readers. They hear "Full name required" instead, from `requiredLabel`. When both `required` and `optional` are set, `required` wins.
- Translate the built-in text with `requiredLabel` (default "required") and `optionalLabel` (default "Optional").
