Search code examples
reactjsimagesrc

React image slider src issue


Im trying too make a slider in react with image src set from an array, i later want too be changing based on the url. but iv run into a problem i cant seem to solve, the returned img`s is getting scr='[object Object]' and i cant seem too figure out why

import { useState, useEffect } from 'react';
import './slider.css'
const sliderSource = [  { id: 1, src: '../../resources/imgs/clutchscrewdrivers1.jpg', alt: 'slidercontent' },
                        { id: 2, src: '../../resources/imgs/currentcontrolledscrewdrivers2.jpg', alt: 'slidercontent' },
                        { id: 3, src: '../../resources/imgs/transducerizedscrewdrivers3.jpg', alt: 'slidercontent' },
                     ];
export function Slideshow() {
  const [index, setIndex] = useState(0);
 
  useEffect(() => {
    const timeout = setTimeout(() => setIndex((prevIndex) =>
    prevIndex === sliderSource.length - 1 ? 0 : prevIndex + 1
  ),5000)
 
    return () => clearTimeout(timeout)
}, [index])
  return (
    <div className="slideshow">
      <div
        className="slideshowSlider"
        style={{ transform: `translate3d(${-index * 100}%, 0, 0)` }}
      >
        {sliderSource.map((src, id, alt) => (
          <img
            className="slide"
            src={ src }
            key={id}
            alt={alt}
          />
        ))}
      </div>

      <div className="slideshowDots">
        {sliderSource.map((_, idx) => (
          <div
            key={idx}
            className={`slideshowDot${index === idx ? " active" : ""}`}
            onClick={() => {
                setIndex(idx);
              }}
          ></div>
        ))}
      </div>
    </div>
  );
}

cant seem too solve the issue


Solution

  • Please check on the map function parameters from here.

    The first param in callback is the element that can be destructed as follows to get desired result

    {sliderSource.map(({src, id, alt}) => (
          <img
            className="slide"
            src={ src }
            key={id}
            alt={alt}
          />
        ))}