Autor:
    Creación:2024-08-11Última actualización:2025-06-29

    Enumeración / Plurialización

    Cómo Funciona la Enumeración

    En Intlayer, la enumeración se logra mediante la función enu, que asigna claves específicas a su contenido correspondiente. Estas claves pueden representar valores numéricos, rangos o identificadores personalizados. Cuando se usa con React Intlayer o Next Intlayer, el contenido apropiado se selecciona automáticamente según la configuración regional de la aplicación y las reglas definidas.

    Configuración de la Enumeración

    Para configurar la enumeración en tu proyecto Intlayer, necesitas crear un módulo de contenido que incluya definiciones de enumeración. Aquí tienes un ejemplo de una enumeración simple para el número de coches:

    **/*.content.ts
    import { enu, type Dictionary } from "intlayer";
    
    const carEnumeration = {
      key: "car_count",
      content: {
        numberOfCar: enu({
          "<-1": "Menos de menos un coche",
          "-1": "Menos un coche",
          "0": "Sin coches",
          "1": "Un coche",
          ">5": "Algunos coches",
          ">19": "Muchos coches",
          "fallback": "Valor de reserva", // Opcional
        }),
      },
    } satisfies Dictionary;
    
    export default carEnumeration;

    En este ejemplo, enu asigna varias condiciones a contenido específico. Cuando se usa en un componente React, Intlayer puede elegir automáticamente el contenido apropiado basado en la variable dada.

    El orden de declaración es importante en las enumeraciones de Intlayer. La primera declaración válida es la que se seleccionará. Si se aplican múltiples condiciones, asegúrese de que estén ordenadas correctamente para evitar comportamientos inesperados.
    Si no se declara un valor de reserva (fallback), la función devolverá undefined si ninguna clave coincide.

    Uso de Enumeraciones con React Intlayer

    To use enumeration in a React component, you can leverage the useIntlayer hook from the react-intlayer package. This hook retrieves the correct content based on the specified ID. Here's an example of how to use it:

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const CarComponent: FC = () => {
    const { numberOfCar } = useIntlayer("car_count");
    
    return (
      <div>
        <p>
          {
            numberOfCar(0) // Output: No cars
          }
        </p>
        <p>
          {
            numberOfCar(6) // Output: Some cars
          }
        </p>
        <p>
          {
            numberOfCar(20) // Output: Many cars
          }
        </p>
        <p>
          {
            numberOfCar(0.01) // Output: Fallback value
          }
        </p>
      </div>
    );
    };

    Combining Enumeration with Insert for Ordinal Numbers

    To use enumeration in a React component, you can leverage the useIntlayer hook from the react-intlayer package. This hook retrieves the correct content based on the specified ID. Here's an example of how to use it:

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const CarComponent: FC = () => {
    const { numberOfCar } = useIntlayer("car_count");
    
    return (
      <div>
        <p>
          {
            numberOfCar(0) // Output: No cars
          }
        </p>
        <p>
          {
            numberOfCar(6) // Output: Some cars
          }
        </p>
        <p>
          {
            numberOfCar(20) // Output: Many cars
          }
        </p>
        <p>
          {
            numberOfCar(0.01) // Output: Fallback value
          }
        </p>
      </div>
    );
    };

    Using Ordinal Enumeration

    To use this in a React component, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const RankingComponent: FC<{ count: number }> = ({ count }) => {
    const { ordinal } = useIntlayer("ranking_component");
    
    // Get the last digit to determine the correct suffix
    const lastDigit = Math.abs(count) % 10;
    
    return (
      <div>
        <p>
          {
            ordinal(lastDigit)({ count }) // e.g., "5th place" for count=5
          }
        </p>
      </div>
    );
    };

    Additional Resources

    For more detailed information on configuration and usage, refer to the following resources:

    These resources provide further insights into the setup and usage of Intlayer in different environments and with various frameworks.