Search code examples
cssreactjstypescriptsliderinfinity

Title: Creating an infinite logo slider using React and CSS without third-party libraries


I'm working on implementing a logo slider in my React application using CSS. I want the slider to behave as an infinite loop, where the last logo in the slide is followed by the first logo, and this pattern continues indefinitely.

Currently, my implementation in the TSX file looks like this:

<section className={classes['container']}>
    <div className={classes['logosSlide']}>
        {props.clientsContent?.map((client, i) => (
            <span key={i}>{client.attributes.clientName}</span>
        ))}
    </div>
</section>

Could you please guide me on achieving this infinite loop functionality using only React and CSS, without relying on any third-party libraries?

I appreciate any assistance you can provide.


Solution

  • Add CSS styles to your component:

    import React, { useEffect } from 'react';
    import classes from './LogoSlider.module.css';
    
    const LogoSlider = (props) => {
      useEffect(() => {
        const container = document.querySelector(`.${classes.container}`);
        const slide = document.querySelector(`.${classes.logosSlide}`);
    
        const cloneSlide = slide.cloneNode(true);
        container.appendChild(cloneSlide);
      }, []);
    
      return (
        <section className={classes.container}>
          <div className={classes.logosSlide}>
            {props.clientsContent?.map((client, i) => (
              <span key={i}>{client.attributes.clientName}</span>
            ))}
          </div>
        </section>
      );
    };
    
    export default LogoSlider;
    

    Define CSS styles in a separate CSS file (e.g., LogoSlider.module.css):

    .container {
      width: 100%;
      overflow: hidden;
    }
    
    .logosSlide {
      display: flex;
      animation: slide infinite 20s linear;
    }
    
    @keyframes slide {
      0% {
        transform: translateX(0);
      }
      100% {
        transform: translateX(-100%);
      }
    }