Reputation: 1518
here i need to control carousel slides with custom buttons i achieved this with the help of this Example.
This is the code for it..
import React, { useState } from "react";
import { Carousel, Button, Container, Row } from "react-bootstrap";
import Cards from "../cards";
import "./slider.css";
const Slider = () => {
const [index, setIndex] = useState(0);
const handleSelect = (selectedIndex, e) => {
setIndex(selectedIndex);
};
const onPrevClick = () => {
if (index > 0) {
setIndex(index - 1);
} else if (index === 0) setIndex(2);
};
const onNextClick = () => {
if (index === 2) {
setIndex(0);
} else if (index === 0 || index > 0) setIndex(index + 1);
};
return (
<>
<div className="button-container">
<Container>
<Row>
<Button variant="primary" onClick={onPrevClick}>
Previous
</Button>
<Button variant="primary" onClick={onNextClick}>
Next
</Button>
</Row>
</Container>
</div>
<Carousel
activeIndex={index}
onSelect={handleSelect}
indicators={false}
controls={false}
>
<Carousel.Item>
<Cards />
</Carousel.Item>
<Carousel.Item>
<Cards />
</Carousel.Item>
<Carousel.Item>
<Cards />
</Carousel.Item>
</Carousel>
</>
);
};
export default Slider;
But when the active index is in last item that means in the last carousel slide. When i press the next button, it moves all the way around from last carousel to first carousel, i.e the direction is like 3 -> 2 -> 1.
I know that something i made terrible logic in the onClick functions. So i am seeking help to suggest me the best way to control carousel slides with custom buttons , your help is much appreciated. Please review my code and tell me any suggestions. Thanks in advance.
And here is the code sandbox link
Upvotes: 5
Views: 5609