Descripción general del carrusel de React

    El carrusel de Ignite UI for React es un componente ligero y con capacidad de respuesta que proporciona la forma más flexible de crear una experiencia web similar a una presentación de diapositivas para los usuarios que navegan hacia adelante y hacia atrás a través de una colección de imágenes con diapositivas de texto, enlaces y otros elementos html.

    El componente Carrusel React le permite usar animaciones, transiciones de diapositivas y personalización para que pueda ajustar fácilmente la interfaz y crear React carrusel personalizado.

    La demostración de React Carousel que ve a continuación muestra diapositivas que contienen solo imágenes.

    Uso

    Primero, debes instalar el paquete npm Ignite UI for React correspondiente ejecutando el siguiente comando:

    npm install igniteui-react
    

    Luego tendrás que importar elIgrCarousel CSS necesario y registrar su módulo, así:

    import { IgrCarousel, IgrCarouselSlide } from 'igniteui-react';
    import 'igniteui-webcomponents/themes/light/bootstrap.css';
    

    Para una introducción completa al Ignite UI for React, lee el tema Empezar.

    Now that you have the Ignite UI for React Carousel imported, you can start with a basic configuration of the IgrCarousel and its slides.

    Use the IgrCarousel selector to wrap your slides. The slides may feature any valid html content inside, including other components.

    <IgrCarousel>
        <IgrCarouselSlide>
            <img src="assets/images/carousel/ignite-ui-angular-indigo-design.png"/>
        </IgrCarouselSlide>
        <IgrCarouselSlide>
            <img src="assets/images/carousel/slider-image-chart.png"/>
        </IgrCarouselSlide>
        <IgrCarouselSlide>
            <img src="assets/images/carousel/ignite-ui-angular-charts.png"/>
        </IgrCarouselSlide>
    </IgrCarousel>
    

    If you want a slide to be active by default, use the Active attribute:

    <IgrCarousel>
        ...
        <IgrCarouselSlide>
            ...
        </IgrCarouselSlide>
        <IgrCarouselSlide active={true}>
            ...
        </IgrCarouselSlide>
    </IgrCarousel>
    

    [! NOTA] Si no hay ningún deslizamiento activo, el primero se configurará por defecto. Si hay varias diapositivas activas en el renderizado inicial o en actualizaciones posteriores, solo se tendrá en cuenta la última.

    Ejemplos

    By default, the IgrCarousel has its disableLoop property set to false (looping occurs when the first slide comes after the last by navigating using the Next action, or when the last slide comes after the first by using the Previous action). The looping behavior can be disabled by setting the value of the disableLoop property to true.

    <IgrCarousel disableLoop={true}>
        ...
    </IgrCarousel>
    

    To keep track of each slide index, the carousel has indicators that are positioned at the end of the carousel by default. In order to change this behavior, use the indicatorsOrientation property and assign it to start.

    <IgrCarousel indicatorsOrientation={CarouselIndicatorsOrientation.Start}>
        ...
    </IgrCarousel>
    

    By default, the IgrCarousel displays its navigation buttons and indicators. Use the hideIndicators property to hide the indicators and the hideNavigation property to hide the navigation buttons.

    <IgrCarousel hideNavigation={true} hideIndicators={true}>
        ...
    </IgrCarousel>
    

    The IgrCarousel supports vertical mode. Use the vertical property to enable it.

    <IgrCarousel vertical={true}>
        ...
    </IgrCarousel>
    

    Indicadores personalizados

    To add React custom carousel indicators, use the IgrCarouselIndicator:

    <IgrCarousel>
      <IgrCarouselIndicator>
        <span key="empty">🤍</span>
        <span slot="active">
          ❤️
        </span>
      </IgrCarouselIndicator>
      <IgrCarouselIndicator>
        <span key="empty">🤍</span>
        <span slot="active">
          ❤️
        </span>
      </IgrCarouselIndicator
      <IgrCarouselSlide>
        <img
          src="https://es.infragistics.com/angular-demos-lob/assets/images/carousel/ignite-ui-angular-indigo-design.png"
        />
      </IgrCarouselSlide>
      <IgrCarouselSlide key="second">
        <img src="https://es.infragistics.com/angular-demos-lob/assets/images/carousel/slider-image-chart.png"/>
      </IgrCarouselSlide>
    </IgrCarousel>
    

    El componente Carrusel Ignite UI for React permite a los usuarios utilizar diferentes elementos para el estado activo e inactivo de un solo indicador. Es obligatorio proporcionar dos elementos para cada ranura (vacío y activo) al declarar un indicador, incluso si son los mismos.

    Custom navigation buttons

    To achieve this, use the previous-button and next-button slots:

    <IgrCarousel>
        <IgrIcon slot="previous-button" name="previous" collection="material"></IgrIcon>
        <IgrIcon slot="next-button" name="next" collection="material"></IgrIcon>
        ...
    </IgrCarousel>
    

    Diapositiva que contiene otros componentes.

    Este carrusel contendrá diapositivas con formularios e imágenes:

    <IgrCarousel>
        <IgrCarouselSlide>
          <div>
            <img src="assets/images/svg/carousel/SignUp.svg" />
            <form>
              <IgrInput type="text" placeholder="Username">
                <IgrIcon slot="prefix" name="person"></IgrIcon>
              </IgrInput>
              <IgrInput type="password" placeholder="Password">
                <IgrIcon slot="prefix" name="password"></IgrIcon>
              </IgrInput>
              <IgrButton type="reset">
                <span>Sign In</span>
              </IgrButton>
            </form>
          </div>
        </IgrCarouselSlide>
        <IgrCarouselSlide>
          <div>
            <img src="assets/images/svg/carousel/Route.svg" />
            <form>
              <IgrInput type="text" placeholder="Search">
                <IgrIcon slot="prefix" name="search"></IgrIcon>
              </IgrInput>
              <IgrButton type="reset">
                <span>Search</span>
              </IgrButton>
            </form>
          </div>
        </IgrCarouselSlide>
    </IgrCarousel>
    

    Manifestación

    animaciones

    Las transiciones de diapositivas animadas brindan a los usuarios finales una experiencia agradable al interactuar con el carrusel.

    The carousel is configured to use the slide animation by default, but it also supports fade as an alternative animation.

    Use the animationType property to change the animation.

    <IgrCarousel animationType="fade">
        ...
    </IgrCarousel>
    

    Setting none to the animationType property disables the animations.

    Manifestación

    La siguiente demostración muestra los diferentes tipos de animaciones que admite el carrusel.

    La transición y la navegación son las características más importantes del carrusel.

    La navegación en el carrusel puede ser manejada por el usuario a través de botones de navegación, indicadores, navegación con el teclado e interacción táctil en dispositivos móviles.

    Gestos táctiles

    De forma predeterminada, el carrusel se puede usar en cualquier dispositivo táctil.

    Las animaciones del carrusel son totalmente compatibles con dispositivos táctiles, lo que hace que el carrusel sea consistente con cualquier plataforma y excelente cuando se usa en aplicaciones web progresivas (PWA).

    Navegación por teclado

    • Botones de navegación
      • SPACE o ENTER clave: navega a la diapositiva siguiente/anterior.
    • Indicadores
      • 🡐 key: navega a la diapositiva anterior (siguiente en modo de derecha a izquierda).
      • 🡒- navega a la siguiente diapositiva (anterior en modo de derecha a izquierda).
      • HOME key: navega a la primera diapositiva (última en modo de derecha a izquierda).
      • END key: navega hasta la última diapositiva (la primera en el modo de derecha a izquierda).

    Transición automática

    The IgrCarousel can be easily configured to change the slides automatically, without any user interaction. This way you can create your own slideshow by only setting a transition interval to the interval property, which determines the amount of time in milliseconds between slides transition.

    [!NOTE] Hovering the mouse over any carousel content or moving keyboard focus to any of the carousel content pauses automatic transitioning. Automatic transitioning resumes when the mouse moves away from the carousel or when keyboard focus moves out of the carousel content. This can be prevented by setting disablePauseOnInteraction property to true.

    <IgrCarousel interval={2000} disablePauseOnInteraction={true}>
        ...
    </IgrCarousel>
    

    Ejemplo avanzado

    Vamos a crear un carrusel totalmente automatizado con el bucle activado. Configuraremos los indicadores para que sean una representación en miniatura de cada diapositiva.

    Para lograr este objetivo, tenemos que realizar las siguientes configuraciones al carrusel:

    Nuestro carrusel se verá así en la plantilla:

    const images = [
        {
            src: "assets/images/carousel/WonderfulCoast.png",
            alt: "Wonderful Coast",
        },
        {
            src: "assets/images/carousel/CulturalDip.png",
            alt: "Cultural Dip",
        },
        {
            src: "assets/images/carousel/GoldenBeaches.png",
            alt: "Golden Beaches",
        },
        {
            src: "assets/images/carousel/IslandOfHistory.png",
            alt: "Island Of History",
        },
        {
            src: "assets/images/carousel/AmazingBridge.png",
            alt: "Amazing Bridge",
        },
    ];
    
    <IgrCarousel
      disablePauseOnInteraction={true}
      hideNavigation={true}
      interval={2000}
      vertical={true}
      animationType="fade"
    >
      {images.map((image, index) => {
        return (
          <React.Fragment key={index}>
            <IgrCarouselSlide>
              <img src={image.src} alt={image.alt} />
            </IgrCarouselSlide>
            <IgrCarouselIndicator>
              <img
                className="blurred"
                src={image.src.replace(".png", "Thumb.png")}
                alt={`${image.alt} Thumb`}
                width="50"
                height="60"
              />
              <img
                slot="active"
                src={image.src.replace(".png", "Thumb.png")}
                alt={`${image.alt} Thumb Active`}
                width="50"
                height="60"
              />
            </IgrCarouselIndicator>
          </React.Fragment>
        );
      })}
    </IgrCarousel>
    

    Estas configuraciones tendrán el siguiente resultado:

    Accesibilidad

    Funciones, estados y propiedades de WAI-ARIA

    • The Carousel base element role is region - section containing content that is relevant to specific purpose and users will likely want to be able to navigate easily.
    • Carousel indicators are with role tab - grouping label providing a mechanism for selecting the tab content that is to be rendered to the user
    • The element that serves as the container for the set of tabs (carousel indicators) is with role tablist.
    • Each slide element is set with role tabpanel.

    Soporte ARIA

    • Attributes
      • aria-roledescription establecido en "carrusel".
      • aria-live - used to set the priority with which screen reader should treat updates to live regions - the possible settings are: off and polite. The default setting is polite and is set to the element that serves as the container for the set of slides. When the interval option is set and the carousel is in playing state, the aria-live attribute would be set to off.
      • aria-label (navigation buttons) - "Previous slide"/"Next slide".

    Slide component

    • Attributes
      • id - sigue el patrón "igc-carousel-slide-${incremented_number}".
      • aria-roledescription establecido en "slide".
      • aria-label sigue el patrón "${index + 1} of ${total}".

    Indicator component

    • Attributes
      • aria-label sigue el patrón "Slide ${index + 1}"
      • Aria-Selected se establece en verdadero o falso en función de la diapositiva activa.

    Referencias de API

    Recursos adicionales