Visão geral do carrossel React

    O carrossel Ignite UI for React é um componente leve e responsivo que fornece a maneira mais flexível de criar uma experiência na Web semelhante a uma apresentação de slides para usuários que navegam para frente e para trás em uma coleção de imagens com slides de texto, links e outros elementos html.

    O componente Carrossel React permite que você use animações, transições de slides e personalização para que você possa ajustar facilmente a interface e criar React carrossel personalizado.

    A demonstração do carrossel React que você vê abaixo mostra slides contendo apenas imagens.

    Uso

    Primeiro, você precisa instalar o pacote npm Ignite UI for React correspondente executando o seguinte comando:

    npm install igniteui-react
    

    You will then need to import the IgrCarousel, its necessary CSS, and register its module, like so:

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

    Para obter uma introdução completa ao Ignite UI for React, leia o tópico Introdução.

    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] Se nenhum slide ativo estiver ativado, o primeiro será configurado por padrão. Se houver vários slides ativos na renderização inicial ou atualizações subsequentes, apenas o último será considerado.

    Exemplos

    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://pt-br.infragistics.com/angular-demos-lob/assets/images/carousel/ignite-ui-angular-indigo-design.png"
        />
      </IgrCarouselSlide>
      <IgrCarouselSlide key="second">
        <img src="https://pt-br.infragistics.com/angular-demos-lob/assets/images/carousel/slider-image-chart.png"/>
      </IgrCarouselSlide>
    </IgrCarousel>
    

    O componente Ignite UI for React carrossel permite que os usuários usem diferentes elementos para o estado ativo e inativo de um único indicador. É obrigatório fornecer dois elementos para cada slot (vazio e ativo) ao declarar um indicador, mesmo que sejam iguais.

    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>
    

    Slide contendo outros componentes

    Este carrossel conterá slides com formulários e imagens:

    <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>
    

    Demo

    Animações

    Transições de slides animadas proporcionam aos usuários finais uma experiência agradável ao interagir com o carrossel.

    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.

    Demo

    A demonstração abaixo demonstra os diferentes tipos de animações que o carrossel suporta.

    Transição e navegação são os recursos mais importantes do carrossel.

    A navegação no carrossel pode ser tratada pelo usuário por meio de botões de navegação, indicadores, navegação por teclado e interação por toque em dispositivos móveis.

    Gestos de toque

    Por padrão, o carrossel pode ser usado em qualquer dispositivo habilitado para toque.

    As animações de carrossel são totalmente suportadas em dispositivos touch, o que torna o carrossel consistente com qualquer plataforma e ótimo quando usado em aplicativos web progressivos (PWA).

    Navegação pelo teclado

    • Botões de navegação
      • SPACE ou ENTER chave - navega para o slide seguinte/anterior.
    • Indicadores
      • 🡐 key - navega para o slide anterior (próximo no modo Da direita para a esquerda).
      • 🡒 key - navega para o próximo slide (anterior no modo Da direita para a esquerda).
      • HOME key - navega até o primeiro slide (último no modo Da direita para a esquerda).
      • END key - navega até o último slide (primeiro no modo da direita para a esquerda).

    Transição 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>
    

    Exemplo avançado

    Vamos criar um carrossel totalmente automatizado com looping ativado. Configuraremos os indicadores para serem uma representação em miniatura de cada slide.

    Para atingir esse objetivo, temos que fazer as seguintes configurações no carrossel:

    Nosso carrossel ficará assim no modelo:

    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>
    

    Essas configurações terão o seguinte resultado:

    Acessibilidade

    Papéis, Estados e Propriedades da 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.

    Suporte ao ARIA

    • Attributes
      • aria-roledescription definido como "carrossel".
      • 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 - segue o padrão "igc-carousel-slide-${incremented_number}".
      • aria-roledescription definido como "slide".
      • aria-label segue o padrão "${index + 1} de ${total}".

    Indicator component

    • Attributes
      • aria-label segue o padrão "Slide ${index + 1}"
      • ARIA-SELECTED definido como verdadeiro ou falso com base no slide ativo.

    Referências de API

    Recursos adicionais