Simple Carousel React
Tue Jun 14 2022 12:18:49 GMT+0000 (Coordinated Universal Time)
Saved by
@jen_magpantay
#javascript
#react.js
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>
);
};
content_copyCOPY
Comments