-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCarouselContainer.jsx
83 lines (74 loc) · 2.69 KB
/
CarouselContainer.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import "./CarouselContainer.css";
import { Children, useRef, useState } from "react";
import LeftIcon from "../assets/left.svg?react";
import RightIcon from "../assets/right.svg?react";
function CarouselContainer(props) {
const { className, children, alt } = props;
const [activePage, setActivePage] = useState(0);
const containerRef = useRef();
const pageCount = Children.count(children);
const canNavigateRight = activePage < pageCount - 1;
const canNavigateLeft = activePage > 0;
const onScroll = (e) => {
const pageWidth = e.target.scrollWidth / pageCount;
const page = Math.round(e.target.scrollLeft / pageWidth);
setActivePage(page);
};
const onNavigateRight = () => {
const current = containerRef.current;
if (current) {
const pageWidth = current.scrollWidth / pageCount;
current.scrollTo({ left: pageWidth * (activePage + 1), behavior: "smooth" });
}
};
const onNavigateLeft = () => {
const current = containerRef.current;
if (current) {
const pageWidth = current.scrollWidth / pageCount;
current.scrollTo({ left: pageWidth * (activePage - 1), behavior: "smooth" });
}
};
const getPaginator = () => {
if (pageCount > 1) {
return (
<div className='carousel-paginator'>
{Children.map(children, (_, index) =>
<div className={`carousel-page-icon ${index === activePage ? "active" : ""}`} />
)}
</div>
);
}
return null;
};
return (
<div className={`carousel-wrapper ${className}`}>
<div className="carousel-container" onScroll={onScroll} ref={containerRef}>
{Children.map(children, (child) => (
<div className="carousel-page">
{child}
</div>
))}
</div>
{getPaginator()}
{canNavigateLeft && (
<button className='carousel-navigator left' onClick={onNavigateLeft}>
<LeftIcon
width="20"
height="20"
alt={alt.left}
/>
</button>
)}
{canNavigateRight && (
<button className='carousel-navigator right' onClick={onNavigateRight}>
<RightIcon
width="20"
height="20"
alt={alt.right}
/>
</button>
)}
</div>
);
}
export default CarouselContainer;