1

I've never built a React slider before and I'm struggling a bit with making it an infinite loop of slides. Currently there are two slides, but I'd like to make it so that the user can click the next/previous buttons and the slides are infinite, repeating slide 1 and slide 2, over and over.

I have built a container for the slide content called Testimonial. The width of the container is 800px.

The slider has next and prev buttons to have the slider move left and right.

Slider.tsx

import React, { useState } from 'react';
import styled from '@emotion/styled';
import Img from 'gatsby-image';
import { SliderTypes } from '../../@types/types';
import Testimonial from '../components/Testimonial';

const Slider = (props: SliderTypes) => {

  const sliderData = [
    {
      index: 0,
      image: 'image',
      header: 'Header text',
      testimonial: 'Testimonial description',
    },
    {
      index: 1,
      image: 'image',
      header: 'Header text',
      testimonial: 'Testimonial description',
    },
  ];

  const [properties, setProperties] = useState(sliderData);
  const [property, setProperty] = useState(sliderData[0]);

  const nextProperty = () => {
    const newIndex = property.index + 1;
    setProperty(properties[newIndex]);
  };

  const prevProperty = () => {
    const newIndex = property.index - 1;
    setProperty(properties[newIndex]);
  };

  return (
    <>
      <button
        onClick={() => nextProperty()}
        disabled={property.index === properties.length - 1}
      >
        Next
      </button>
      <button onClick={() => prevProperty()} disabled={property.index === 0}>
        Prev
      </button>

      <CardSlider className={`card-slider active-slide-${property.index}`}>
        <CardSliderWrapper
          style={{
            transform: `translateX(-${
              property.index * (200 / properties.length)
            }%)`,
          }}
        >
          {sliderData.map(({ index, image, header, testimonial }) => (
            <Testimonial
              key={index}
              images={image}
              header={header}
              testimonial={testimonial}
            />
          ))}
        </CardSliderWrapper>
      </CardSlider>
    </>
  );
};

export default Slider;

I appreciate any insights. Thanks in advance!

Kayla
  • 165
  • 2
  • 4
  • 13

0 Answers0