> Markdown version of [Badge](https://vaadin.com/docs/latest/fr/components/badge). Section index: [llms.txt](https://vaadin.com/docs/latest/fr/components/llms.txt)

# Badge (since V25.1)

Les badges sont des éléments de texte colorés contenant de petites informations. Ils sont utilisés pour étiqueter du contenu, afficher des métadonnées et/ou mettre en évidence des informations.

**Lit** — `badge-basic.ts`

```html
<vaadin-badge>Pending</vaadin-badge>
<vaadin-badge theme="success">Confirmed</vaadin-badge>
<vaadin-badge theme="warning">Warning</vaadin-badge>
<vaadin-badge theme="error">Denied</vaadin-badge>
```

**Flow** — `BadgeBasic.java`

```java
Badge pending = new Badge("Pending");

Badge confirmed = new Badge("Confirmed");
confirmed.addThemeVariants(BadgeVariant.SUCCESS);

Badge warning = new Badge("Warning");
warning.addThemeVariants(BadgeVariant.WARNING);

Badge denied = new Badge("Denied");
denied.addThemeVariants(BadgeVariant.ERROR);
```

**React** — `badge-basic.tsx`

```tsx
<Badge>Pending</Badge>
<Badge theme="success">Confirmed</Badge>
<Badge theme="warning">Warning</Badge>
<Badge theme="error">Denied</Badge>
```

## <a id="libellé"></a>Libellé

Les badges devraient contenir un libellé. Les libellés devraient être clairs, concis, et rédigés en casse de phrase. Visez 1 à 2 mots.

## <a id="icônes"></a>Icônes

Les badges peuvent contenir des icônes ainsi que du texte. Les icônes sont placées avant le texte en utilisant le slot `icon`.

**Lit** — `badge-icons.ts`

```html
<vaadin-horizontal-layout theme="spacing">
  <vaadin-badge>
    <vaadin-icon icon="vaadin:clock" slot="icon"></vaadin-icon>
    Pending
  </vaadin-badge>
  <vaadin-badge theme="success">
    <vaadin-icon icon="vaadin:check" slot="icon"></vaadin-icon>
    Confirmed
  </vaadin-badge>
  <vaadin-badge theme="warning">
    <vaadin-icon icon="vaadin:warning" slot="icon"></vaadin-icon>
    Warning
  </vaadin-badge>
  <vaadin-badge theme="error">
    <vaadin-icon icon="vaadin:exclamation-circle-o" slot="icon"></vaadin-icon>
    Denied
  </vaadin-badge>
</vaadin-horizontal-layout>
```

**Flow** — `BadgeIcons.java`

```java
Badge pending = new Badge("Pending", VaadinIcon.CLOCK.create());

Badge confirmed = new Badge("Confirmed", VaadinIcon.CHECK.create());
confirmed.addThemeVariants(BadgeVariant.SUCCESS);

Badge warning = new Badge("Warning", VaadinIcon.WARNING.create());
warning.addThemeVariants(BadgeVariant.WARNING);

Badge denied = new Badge("Denied",
        VaadinIcon.EXCLAMATION_CIRCLE_O.create());
denied.addThemeVariants(BadgeVariant.ERROR);
```

**React** — `badge-icons.tsx`

```tsx
<HorizontalLayout theme="spacing">
  <Badge>
    <Icon icon="vaadin:clock" slot="icon" />
    Pending
  </Badge>
  <Badge theme="success">
    <Icon icon="vaadin:check" slot="icon" />
    Confirmed
  </Badge>
  <Badge theme="warning">
    <Icon icon="vaadin:warning" slot="icon" />
    Warning
  </Badge>
  <Badge theme="error">
    <Icon icon="vaadin:exclamation-circle-o" slot="icon" />
    Denied
  </Badge>
</HorizontalLayout>
```

> **Note: Utilisez les icônes avec parcimonie**
>
> L’avantage d’utiliser des icônes devrait être mis en balance avec le bruit visuel que cela ajoute.

### <a id="icône-uniquement"></a>Icône uniquement

Les badges peuvent aussi être utilisés avec des icônes sans libellé. Pour l’accessibilité, le texte devrait tout de même être fourni lors de l’utilisation de la variante de style `icon-only`. Il est uniquement masqué visuellement mais disponible pour les lecteurs d’écran afin de garantir que tous les utilisateurs puissent identifier la signification du badge.

**Lit** — `badge-icons-only.ts`

```html
<vaadin-badge theme="success icon-only">
  <vaadin-icon icon="vaadin:check" slot="icon"></vaadin-icon>
  Confirmed
</vaadin-badge>
<vaadin-badge theme="error icon-only">
  <vaadin-icon icon="vaadin:close-small" slot="icon"></vaadin-icon>
  Cancelled
</vaadin-badge>
```

**Flow** — `BadgeIconsOnly.java`

```java
Badge confirmed = new Badge("Confirmed", VaadinIcon.CHECK.create());
confirmed.addThemeVariants(BadgeVariant.SUCCESS,
        BadgeVariant.ICON_ONLY);

Badge cancelled = new Badge("Cancelled",
        VaadinIcon.CLOSE_SMALL.create());
cancelled.addThemeVariants(BadgeVariant.ERROR, BadgeVariant.ICON_ONLY);
```

**React** — `badge-icons-only.tsx`

```tsx
<Badge theme="success icon-only">
  <Icon icon="vaadin:check" slot="icon" />
  Confirmed
</Badge>
<Badge theme="error icon-only">
  <Icon icon="vaadin:close-small" slot="icon" />
  Cancelled
</Badge>
```

Les badges à icône uniquement devraient principalement être utilisés pour du contenu courant récurrent avec des icônes hautement standardisées, universellement comprises (comme une coche pour "*yes*"), et pour du contenu répété, par exemple dans des listes et des tableaux.

**Lit** — `badge-icons-only-table.ts`

```typescript
const renderBoolean: GridColumnBodyLitRenderer<UserPermissions> = (item, _model, column) => {
  let icon: string;
  let title: string;
  let theme: string;

  if (item[column.id as keyof UserPermissions]) {
    icon = 'vaadin:check';
    title = 'Yes';
    theme = 'success';
  } else {
    icon = 'vaadin:close-small';
    title = 'No';
    theme = 'error';
  }

  return html`
    <vaadin-badge theme="${theme} icon-only">
      <vaadin-icon icon="${icon}" slot="icon"></vaadin-icon>
      ${title}
    </vaadin-badge>
  `;
};

return html`
  <vaadin-grid .items="${this.items}">
    <vaadin-grid-column path="name" header="Name"></vaadin-grid-column>
    <vaadin-grid-column
      id="view"
      header="View"
      ${columnBodyRenderer(renderBoolean, [])}
    ></vaadin-grid-column>
    <vaadin-grid-column
      id="comment"
      header="Comment"
      ${columnBodyRenderer(renderBoolean, [])}
    ></vaadin-grid-column>
    <vaadin-grid-column
      id="edit"
      header="Edit"
      ${columnBodyRenderer(renderBoolean, [])}
    ></vaadin-grid-column>
  </vaadin-grid>
`;
```

**Flow** — `BadgeIconsOnlyTable.java`

```java
grid.addColumn(UserPermissions::getName).setHeader("Name");
grid.addComponentColumn(userPermissions -> createPermissionBadge(
        userPermissions.getView())).setHeader("View");
grid.addComponentColumn(userPermissions -> createPermissionBadge(
        userPermissions.getComment())).setHeader("Comment");
grid.addComponentColumn(userPermissions -> createPermissionBadge(
        userPermissions.getEdit())).setHeader("Edit");

...

private Badge createPermissionBadge(boolean hasPermission) {
    Badge badge;
    if (hasPermission) {
        badge = new Badge("Yes", VaadinIcon.CHECK.create());
        badge.addThemeVariants(BadgeVariant.SUCCESS,
                BadgeVariant.ICON_ONLY);
    } else {
        badge = new Badge("No", VaadinIcon.CLOSE_SMALL.create());
        badge.addThemeVariants(BadgeVariant.ERROR, BadgeVariant.ICON_ONLY);
    }
    return badge;
}
```

**React** — `badge-icons-only-table.tsx`

```tsx
const renderBadge = ({
  item,
  original: column,
}: {
  item: any;
  original: GridColumnElement<UserPermissions>;
}) => {
  let icon;
  let title;
  let theme;

  if (item[column.id]) {
    icon = 'vaadin:check';
    title = 'Yes';
    theme = 'success';
  } else {
    icon = 'vaadin:close-small';
    title = 'No';
    theme = 'error';
  }

  return (
    <Badge theme={`${theme} icon-only`}>
      <Icon icon={icon} slot="icon" />
      {title}
    </Badge>
  );
};

return (
  <Grid items={items.value}>
    <GridColumn path="name" header="Name" />
    <GridColumn id="view" header="View" renderer={renderBadge} />
    <GridColumn id="comment" header="Comment" renderer={renderBadge} />
    <GridColumn id="edit" header="Edit" renderer={renderBadge} />
  </Grid>
);
```

## <a id="nombre"></a>Nombre

Les badges peuvent afficher une valeur numérique en utilisant la propriété `number`. Ceci est utile pour afficher des comptes, tels que des messages non lus ou des notifications. Lorsque le contenu texte et un nombre sont tous deux définis, les deux sont affichés.

**Lit** — `badge-number.ts`

```html
<vaadin-badge number="12">New messages</vaadin-badge>
<vaadin-badge number="3" theme="success">Completed</vaadin-badge>
<vaadin-badge number="1" theme="error">Failed</vaadin-badge>
```

**Flow** — `BadgeNumber.java`

```java
Badge inbox = new Badge("New messages", 12);

Badge completed = new Badge("Completed", 3);
completed.addThemeVariants(BadgeVariant.SUCCESS);

Badge failed = new Badge("Failed", 1);
failed.addThemeVariants(BadgeVariant.ERROR);
```

**React** — `badge-number.tsx`

```tsx
<Badge number={12}>New messages</Badge>
<Badge number={3} theme="success">
  Completed
</Badge>
<Badge number={1} theme="error">
  Failed
</Badge>
```

### <a id="nombre-uniquement"></a>Nombre uniquement

Les badges peuvent afficher un nombre sans libellé visible en utilisant la variante de style `number-only`. Pour l’accessibilité, le libellé texte devrait tout de même être fourni — il est uniquement masqué visuellement mais disponible pour les lecteurs d’écran afin de garantir que tous les utilisateurs puissent identifier la signification du badge.

**Lit** — `badge-number-only.ts`

```html
<vaadin-badge number="12" theme="number-only">New messages</vaadin-badge>
<vaadin-badge number="3" theme="error number-only">Alerts</vaadin-badge>
```

**Flow** — `BadgeNumberOnly.java`

```java
Badge inbox = new Badge("New messages", 12);
inbox.addThemeVariants(BadgeVariant.NUMBER_ONLY);

Badge alerts = new Badge("Alerts", 3);
alerts.addThemeVariants(BadgeVariant.ERROR, BadgeVariant.NUMBER_ONLY);
```

**React** — `badge-number-only.tsx`

```tsx
<Badge number={12} theme="number-only">
  New messages
</Badge>
<Badge number={3} theme="error number-only">
  Alerts
</Badge>
```

## <a id="cas-dutilisation"></a>Cas d’utilisation

### <a id="mise-en-évidence-et-distinction-des-informations"></a>Mise en évidence et distinction des informations

Un cas d’utilisation typique des badges est de mettre en évidence le statut d’un élément, par exemple dans un Grid.

**Lit** — `badge-highlight.ts`

```typescript
return html`
  <vaadin-grid .items="${this.items}">
    <vaadin-grid-column path="report" header="Report"></vaadin-grid-column>
    <vaadin-grid-column
      header="Due date"
      ${columnBodyRenderer<Report>(
        ({ due }) => html`${dateFormatter.format(new Date(due))}`,
        []
      )}
    ></vaadin-grid-column>
    <vaadin-grid-column path="assignee" header="Assignee"></vaadin-grid-column>
    <vaadin-grid-column
      header="Status"
      ${columnBodyRenderer<Report>(({ status }) => {
        let title: string;
        let theme: string;

        switch (status) {
          case ReportStatus.COMPLETED:
            title = 'Completed';
            theme = 'success';
            break;
          case ReportStatus.IN_PROGRESS:
            title = 'In progress';
            theme = '';
            break;
          case ReportStatus.CANCELLED:
            title = 'Cancelled';
            theme = 'error';
            break;
          case ReportStatus.ON_HOLD:
            title = 'On hold';
            theme = 'warning';
            break;
        }

        return html`<vaadin-badge theme="${theme} filled">${title}</vaadin-badge>`;
      }, [])}
    ></vaadin-grid-column>
  </vaadin-grid>
`;
```

**Flow** — `BadgeHighlight.java`

```java
grid.addComponentColumn(report -> createStatusBadge(report.getStatus()))
        .setHeader("Status");

...

private Badge createStatusBadge(String status) {
    Badge badge = new Badge(status);
    badge.addThemeVariants(BadgeVariant.FILLED);
    switch (status) {
    case "Completed":
        badge.addThemeVariants(BadgeVariant.SUCCESS);
        break;
    case "Cancelled":
        badge.addThemeVariants(BadgeVariant.ERROR);
        break;
    case "On hold":
        badge.addThemeVariants(BadgeVariant.WARNING);
        break;
    default:
        break;
    }
    return badge;
}
```

**React** — `badge-highlight.tsx`

```tsx
function renderDueDate({ item: report }: { item: Report }) {
  return <span>{dateFormatter.format(new Date(report.due))}</span>;
}

function renderStatus({ item: report }: { item: Report }) {
  let title: string;
  let theme: string;

  switch (report.status) {
    case ReportStatus.COMPLETED:
      title = 'Completed';
      theme = 'success';
      break;
    case ReportStatus.IN_PROGRESS:
      title = 'In progress';
      theme = '';
      break;
    case ReportStatus.CANCELLED:
      title = 'Cancelled';
      theme = 'error';
      break;
    case ReportStatus.ON_HOLD:
      title = 'On hold';
      theme = 'warning';
      break;
  }

  return <Badge theme={`${theme} filled`}>{title}</Badge>;
}

function Example() {
  const items = useSignal<Report[]>([]);
  useEffect(() => {
    getReports().then((reports) => {
      items.value = reports as Report[];
    });
  }, []);

  return (
    <Grid items={items.value}>
      <GridColumn path="report" header="Report" />
      <GridColumn header="Due date" renderer={renderDueDate} />
      <GridColumn path="assignee" header="Assignee" />
      <GridColumn header="Status" renderer={renderStatus} />
    </Grid>
  );
}
```

Ils sont aussi souvent utilisés pour afficher des étiquettes de métadonnées.

### <a id="contenu-interactif"></a>Contenu interactif

Les badges peuvent contenir du contenu interactif tel que des Anchors et des Buttons. Par exemple, des badges qui mettent en évidence des filtres actifs pourraient contenir un Button "Clear" qui supprime le filtre associé.

**Lit** — `badge-interactive.ts`

```typescript
return html`
  <vaadin-vertical-layout theme="spacing">
    <vaadin-combo-box
      label="Profession"
      .items="${this.items}"
      @change="${this.onChange}"
    ></vaadin-combo-box>
    <vaadin-horizontal-layout theme="spacing wrap">
      ${repeat(
        this.selectedProfessions,
        (profession) => profession,
        (profession) => html`
          <vaadin-badge style="padding-right: 0">
            <span>${profession}</span>
            <vaadin-button
              aria-label="Clear filter: ${profession}"
              data-profession="${profession}"
              theme="tertiary"
              title="Clear filter: ${profession}"
              style="height: 1.5rem; min-width: 1.5rem; margin: 0; padding: 0"
              @click="${this.onClick}"
            >
              <vaadin-icon icon="vaadin:close-small"></vaadin-icon>
            </vaadin-button>
          </vaadin-badge>
        `
      )}
    </vaadin-horizontal-layout>
  </vaadin-vertical-layout>
`;
```

**Flow** — `BadgeInteractive.java`

```java
HorizontalLayout badges = new HorizontalLayout();
badges.addThemeNames("wrap");

ComboBox<String> comboBox = new ComboBox<>("Profession");
comboBox.setItems(DataService.getProfessions());
comboBox.addValueChangeListener(e -> {
    Badge filterBadge = createFilterBadge(e.getValue());
    badges.add(filterBadge);
});

...

private Badge createFilterBadge(String profession) {
    Button clearButton = new Button(VaadinIcon.CLOSE_SMALL.create());
    clearButton.addThemeVariants(ButtonVariant.TERTIARY);
    clearButton.getStyle().set("height", "1.5rem")
            .set("min-width", "1.5rem").set("margin", "0")
            .set("padding", "0");
    // Accessible button name
    clearButton.getElement().setAttribute("aria-label",
            "Clear filter: " + profession);
    // Tooltip
    clearButton.getElement().setAttribute("title",
            "Clear filter: " + profession);

    Badge badge = new Badge(profession);
    badge.getStyle().set("padding-right", "0");
    badge.getElement().appendChild(clearButton.getElement());

    // Add handler for removing the badge
    clearButton.addClickListener(event -> {
        badge.getElement().removeFromParent();
    });

    return badge;
}
```

**React** — `badge-interactive.tsx`

```tsx
return (
  <VerticalLayout theme="spacing">
    <ComboBox label="Profession" items={items.value} onChange={onChange} />

    <HorizontalLayout theme="spacing wrap">
      {selectedProfessions.value.map((profession) => (
        <Badge key={profession} style={{ paddingRight: '0' }}>
          <span>{profession}</span>
          <Button
            aria-label={`Clear filter: ${profession}`}
            data-profession={profession}
            theme="tertiary"
            title={`Clear filter: ${profession}`}
            style={{ height: '1.5rem', minWidth: '1.5rem', margin: '0', padding: '0' }}
            onClick={onClick}
          >
            <Icon icon="vaadin:close-small" />
          </Button>
        </Badge>
      ))}
    </HorizontalLayout>
  </VerticalLayout>
);
```

### <a id="compteur"></a>Compteur

Les badges peuvent être utilisés comme compteurs, par exemple pour afficher le nombre de messages non lus/nouveaux, le nombre de sélections, etc.

**Lit** — `badge-counter.ts`

```html
<vaadin-tabs>
  <vaadin-tab>
    <span>Inbox</span>
    <vaadin-badge number="12" theme="filled number-only">unread messages</vaadin-badge>
  </vaadin-tab>
  <vaadin-tab>
    <span>Important</span>
    <vaadin-badge number="3" theme="filled number-only">unread messages</vaadin-badge>
  </vaadin-tab>
  <vaadin-tab>
    <span>Spam</span>
    <vaadin-badge number="45" theme="filled number-only">unread messages</vaadin-badge>
  </vaadin-tab>
  <vaadin-tab>
    <span>Archive</span>
    <vaadin-badge number="23" theme="filled number-only">unread messages</vaadin-badge>
  </vaadin-tab>
</vaadin-tabs>
```

**Flow** — `BadgeCounter.java`

```java
Tabs tabs = new Tabs(createTab("Inbox", 12), createTab("Important", 3),
        createTab("Spam", 45), createTab("Archive", 23));

...

private static Tab createTab(String labelText, int messageCount) {
    Span label = new Span(labelText);
    Badge counter = new Badge("unread messages", messageCount);
    counter.addThemeVariants(BadgeVariant.FILLED, BadgeVariant.NUMBER_ONLY);
    counter.getStyle().set("margin-inline-start", "var(--vaadin-gap-s)");

    return new Tab(label, counter);
}
```

**React** — `badge-counter.tsx`

```tsx
<Tabs>
  <Tab>
    <span>Inbox</span>
    <Badge number={12} theme="filled number-only" style={badgeStyle}>
      unread messages
    </Badge>
  </Tab>
  <Tab>
    <span>Important</span>
    <Badge number={3} theme="filled number-only" style={badgeStyle}>
      unread messages
    </Badge>
  </Tab>
  <Tab>
    <span>Spam</span>
    <Badge number={45} theme="filled number-only" style={badgeStyle}>
      unread messages
    </Badge>
  </Tab>
  <Tab>
    <span>Archive</span>
    <Badge number={23} theme="filled number-only" style={badgeStyle}>
      unread messages
    </Badge>
  </Tab>
</Tabs>
```

Les technologies d’assistance, telles que les lecteurs d’écran, interprètent les badges uniquement en fonction de leur contenu. Sans contexte approprié, elles peuvent finir par dérouter l’utilisateur. Pour fournir du contexte aux personnes utilisant des lecteurs d’écran, définissez l’attribut `aria-label` du badge.

## <a id="bonnes-pratiques"></a>Bonnes pratiques

### <a id="badge-vs-button"></a>Badge vs Button

Les badges et les Buttons sont similaires en apparence. Cela peut amener les utilisateurs à penser que les badges sont interactifs.

L’emplacement, le langage, et la couleur peuvent tous aider à atténuer toute confusion. Premièrement, les badges ne devraient pas être libellés avec des verbes d’action. Ils ne sont pas des actions, mais plutôt du texte/contenu statique. Deuxièmement, évitez de placer des badges directement à côté de Buttons, en particulier s’ils utilisent des thèmes similaires.

`69AF8882-CA67-4AB8-BF9F-69A1EA6CE84C`
