skip to Main Content

create Image slider and import the images and create two buttons like Previous and next to operate the images accordingly

2

Answers


  1. Here you have a link to do it step by step:

    https://reactjsguru.com/how-to-make-image-slider-in-react/

    good luck!

    Login or Signup to reply.
  2. If you want a slider that fetches images using URL, then you could make a simple image slider using the following approach (originally made by imharshm) using React:

    import { useRef, useState } from "react";
    const Photos = [
        "beach", "space", "office", "house", "shops", "hat", "park", "food", "club",
        "dance", "sun", "stars", "friends", "bank", "laptop", "book", "table", "mountain", "school",
        "watch", "bag", "family", "shops", "forrest", "city", "bus", "clock", "train",    "bottle"
    ]
    
    export function App(props) {
      const elementRef = useRef(null);
      const [arrowDisable, setArrowDisable] = useState(true);
      const unsplashed = "https://source.unsplash.com/200x200/";
    
      const handleHorizantalScroll = (element, speed, distance, step) => {
        let scrollAmount = 0;
        const slideTimer = setInterval(() => {
          element.scrollLeft += step;
          scrollAmount += Math.abs(step);
          if (scrollAmount >= distance) {
            clearInterval(slideTimer);
          }
          if (element.scrollLeft === 0) {
            setArrowDisable(true);
          } else {
            setArrowDisable(false);
          }
        }, speed);
      };
    
      return (
        <>
          <div class="button-contianer">
            <button
              onClick={() => {
                handleHorizantalScroll(elementRef.current, 25, 100, -10);
              }}
              disabled={arrowDisable}
            >
              Left
            </button>
            <button
              onClick={() => {
                handleHorizantalScroll(elementRef.current, 25, 100, 10);
              }}
            >
              Right
            </button>
          </div>
          <div class="img-container" ref={elementRef}>
            {Photos.map((placement, i) => (
              <img
                key={i}
                loading="lazy"
                alt={placement}
                src={unsplashed + `?${placement}`}
              />
            ))}
          </div>
        </>
      );
    };
    

    CSS:

    .button-contianer {
      display: flex;
      justify-content: space-between;
    }
    .img-container {
      display: flex;
      overflow: hidden;
      width: 100%;
      border: 5px solid #ffffff;
      border-radius: 10px;
    }
    

    You can see a live demo made by imharshm here:
    https://codesandbox.io/p/sandbox/react-horizontal-scroll-on-button-click-oxcq8?file=%2Fsrc%2FImages.js%3A17%2C38

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search