DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

React Coding Challenge : Image carousel

// App.js
import { useState } from "react";
import "./styles.css";

const images = [
  "https://images.unsplash.com/photo-1501785888041-af3ef285b470?q=80&w=1200",
  "https://images.unsplash.com/photo-1491553895911-0055eca6402d?q=80&w=1200",
  "https://images.unsplash.com/photo-1519681393784-d120267933ba?q=80&w=1200",
];

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Carousel images={images} />
    </div>
  );
}

function Carousel({ images }) {
  const [index, setIndex] = useState(0);

  const prev = () => setIndex((i) => (i - 1 + images.length) % images.length);
  const next = () => setIndex((i) => (i + 1) % images.length);

  return (
    <div className="carousel">
      <button className="nav-btn left" aria-label="Previous" onClick={prev}>
        
      </button>

      <img src={images[index]} alt={`Slide ${index + 1}`} className="slide" />

      <button className="nav-btn right" aria-label="Next" onClick={next}>
        
      </button>

      <div className="dots">
        {images.map((_, i) => (
          <button
            key={i}
            className={`dot ${i === index ? "active" : ""}`}
            onClick={() => setIndex(i)}
            aria-label={`Go to slide ${i + 1}`}
          />
        ))}
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode
/* styles.css */
.App {
  font-family: sans-serif;
  text-align: center;
  padding: 20px;
}

.carousel {
  position: relative;
  width: 640px;
  max-width: 90vw;
  margin: 20px auto;
}

.slide {
  width: 100%;
  height: 360px;
  object-fit: cover;
  border-radius: 10px;
  box-shadow: 0 8px 22px rgba(0, 0, 0, 0.2);
}

.nav-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  border: none;
  background: rgba(0, 0, 0, 0.45);
  color: #fff;
  font-size: 28px;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  cursor: pointer;
}

.nav-btn:hover {
  background: rgba(0, 0, 0, 0.6);
}

.nav-btn.left {
  left: 10px;
}

.nav-btn.right {
  right: 10px;
}

.dots {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 10px;
}

.dot {
  width: 10px;
  height: 10px;
  border: none;
  border-radius: 50%;
  background: #cfcfcf;
  cursor: pointer;
}

.dot.active {
  background: #333;
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)