feat(components): add carousel components
it's inmidiatly used in the image gallery
This commit is contained in:
parent
4f903c3c8d
commit
8f15b45e9b
6 changed files with 162 additions and 83 deletions
66
src/components/Carousel/Carousel.tsx
Normal file
66
src/components/Carousel/Carousel.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import React, { Children, useEffect, useRef, useState } from 'react';
|
||||
import classes from './Carousel.module.css';
|
||||
|
||||
interface Props {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function Carousel({ children }: Props): JSX.Element {
|
||||
const [activeItem, setActiveItem] = useState(0);
|
||||
const content = useRef<HTMLDivElement>(null);
|
||||
const maxItems = Children.count(children) - 1;
|
||||
|
||||
useEffect(() => {
|
||||
if (content.current == null) return;
|
||||
|
||||
const offset = content.current.clientWidth * activeItem;
|
||||
// const offset = 100 * activeItem;
|
||||
//
|
||||
console.log(offset, activeItem, content.current.clientWidth);
|
||||
|
||||
content.current.style.transform = `translate3d(-${offset}px, 0px, 0px)`;
|
||||
}, [activeItem]);
|
||||
|
||||
const offsetActiveItem = (offset: number): void => {
|
||||
setActiveItem((prev) => {
|
||||
const newActiveItem = prev + offset;
|
||||
|
||||
// Wrap on end in both sides
|
||||
if (newActiveItem < 0) {
|
||||
return maxItems;
|
||||
}
|
||||
|
||||
if (newActiveItem > maxItems) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return newActiveItem;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classes.carousel}>
|
||||
<button
|
||||
className={classes.btnPrev}
|
||||
onClick={() => {
|
||||
offsetActiveItem(-1);
|
||||
}}
|
||||
>
|
||||
Prev
|
||||
</button>
|
||||
<div className={classes.container}>
|
||||
<div ref={content} className={classes.content}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className={classes.btnNext}
|
||||
onClick={() => {
|
||||
offsetActiveItem(1);
|
||||
}}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue