Autor:
    Criação:2026-05-04Última atualização:2026-05-04

    Conteúdo Plural / Plural no Intlayer

    Como o Plural Funciona

    To use plural content inside a React component, retrieve it via the useIntlayer hook and call it with a count. The active locale and the count are combined to pick the matching CLDR category.

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const OpeningsComponent: FC<{ count: number }> = ({ count }) => {
    const { totalOpenings } = useIntlayer("total_openings");
    
    return (
      <div>
        <p>{totalOpenings(count)}</p>
      </div>
    );
    };
    
    export default OpeningsComponent;

    Quando usar plural vs enu

    To use plural content inside a React component, retrieve it via the useIntlayer hook and call it with a count. The active locale and the count are combined to pick the matching CLDR category.

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const OpeningsComponent: FC<{ count: number }> = ({ count }) => {
    const { totalOpenings } = useIntlayer("total_openings");
    
    return (
      <div>
        <p>{totalOpenings(count)}</p>
      </div>
    );
    };
    
    export default OpeningsComponent;

    Configurando Conteúdo Plural

    Para configurar o conteúdo plural no seu projeto Intlayer, crie um módulo de conteúdo que use o auxiliar plural. A categoria other é obrigatória e é usada como fallback quando uma localidade não define uma categoria mais específica.

    **/*.content.ts
    import { plural, t, type Dictionary } from "intlayer";
    
    const openingsContent = {
      key: "total_openings",
      content: {
        totalOpenings: t({
          en: plural({
            one: "{{count}} opening",
            other: "{{count}} openings",
          }),
          pt: plural({
            one: "{{count}} vaga",
            other: "{{count}} vagas",
          }),
        }),
      },
    } satisfies Dictionary;
    
    export default openingsContent;

    As categorias suportadas são zero, one, two, few, many, other. Você só precisa declarar as categorias que seu idioma de destino usa, o Intlayer volta para other quando nenhuma categoria específica corresponde.

    O marcador {{count}} é substituído automaticamente pela contagem que você passa em tempo de execução. Você também pode incluir outros marcadores (veja Marcadores personalizados abaixo).

    Usando Conteúdo Plural com React Intlayer

    Para usar conteúdo plural dentro de um componente React, recupere-o através do hook useIntlayer e chame-o com uma contagem. A localidade ativa e a contagem são combinadas para escolher a categoria CLDR correspondente.

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const OpeningsComponent: FC<{ count: number }> = ({ count }) => {
      const { totalOpenings } = useIntlayer("total_openings");
    
      return (
        <div>
          {/* Em inglês:                                  */}
          {/*  count=0  → "0 openings"   (other)           */}
          {/*  count=1  → "1 opening"    (one)             */}
          {/*  count=2  → "2 openings"   (other)           */}
          {/*  count=21 → "21 openings"  (other)           */}
          <p>{totalOpenings(count)}</p>
        </div>
      );
    };
    
    export default OpeningsComponent;

    Você pode chamar a função retornada de duas maneiras equivalentes:

    tsx
    totalOpenings(21); // atalho: apenas contagemtotalOpenings({ count: 21 }); // forma explícita

    Marcadores personalizados

    Strings plurais podem incluir marcadores diferentes de {{count}}. Passe-os na forma de objeto junto com count:

    **/*.content.ts
    import { plural, type Dictionary } from "intlayer";
    
    const inboxContent = {
      key: "inbox_summary",
      content: {
        summary: plural({
          one: "{{name}}, você tem {{count}} nova mensagem",
          other: "{{name}}, você tem {{count}} novas mensagens",
        }),
      },
    } satisfies Dictionary;
    
    export default inboxContent;
    **/*.tsx
    const { summary } = useIntlayer("inbox_summary");
    
    summary({ count: 1, name: "Alice" });
    // → "Alice, você tem 1 nova mensagem"
    
    summary({ count: 7, name: "Alice" });
    // → "Alice, você tem 7 novas mensagens"

    Categorias CLDR em um relance

    Diferentes idiomas usam diferentes subconjuntos das categorias CLDR. Alguns casos comuns:

    Idioma Categorias usadas
    Inglês (en) one, other
    Francês (fr) one, many, other
    Russo (ru) one, few, many, other
    Polonês (pl) one, few, many, other
    Árabe (ar) zero, one, two, few, many, other
    Japonês / Chinês apenas other

    Você não precisa memorizar isso, declare as categorias para as quais você tem traduções, e o Intlayer voltará para other quando necessário.

    Limitação

    Em comparação com outros nós, o plural ainda não pode ser aninhado com nós filhos.

    Exemplo:

    Válido:

    ts
        totalOpenings: t({      en: plural({        one: "{{count}} opening",        other: "{{count}} openings",      }),      fr: plural({        one: "{{count}} offre",        other: "{{count}} offres",      }),    }),

    Inválido:

    ts
    totalOpenings: plural({  one: t({    en: "{{count}} opening",    fr: "{{count}} offre",  }),  other: t({    en: "{{count}} openings",    fr: "{{count}} offres",  }),}),

    Recursos Adicionais

    Para informações mais detalhadas sobre configuração e uso, consulte os seguintes recursos:

    Estes recursos oferecem mais insights sobre a configuração e o uso do Intlayer em vários ambientes e frameworks.