import React, { useState } from "react"; import { Button } from "./Button"; // data is an array of objects const data = [{id:1, url: "https://..."}, ...] import { data } from "../data/carouselData"; export const Carrousel = () => { const [index, setIndex] = useState(0); // when buttons are clicked, the state (index) would increased or decreased // to avoid the code crash when index reachs its min and max values, conditios are set on click events function handlePreviousBtn() { index > 0 ? setIndex(index - 1) : setIndex(data.length - 1); } function handleNextBtn() { index < data.length - 1 ? setIndex(index + 1) : setIndex(0); } return ( // carousel has width 100% and specif height <div className="carousel"> {/* Button is a custom component */} <Button style="carousel--btn left-4" type="button" title="left" onClick={() => handlePreviousBtn()} /> <Button style="carousel--btn right-4" type="button" title="right" onClick={() => handleNextBtn()} /> {/* carousel--item and carousel--item-img has widht and heigth 100% */} <div className="carousel--item"> {/* also carousel--item-img has object-contain style prop */} <img className="carousel--item-img" src={data[index].url} alt="Random Image" /> </div> </div> ); };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter